0

I have a very simple program, which calculates an equation:

calc = "3 + 18 / 6 * 12 - 2"
ans = exec(calc)
print(ans)

I would like this to print 37, but instead, it returns None. How can I fix this?

martineau
  • 119,623
  • 25
  • 170
  • 301
LogicalX
  • 95
  • 1
  • 10
  • Try using the [`eval()`](https://docs.python.org/3/library/functions.html#eval) function instead, it's for evaluating _expressions_, which is what you appear to be trying to do. – martineau Sep 08 '19 at 02:18
  • 1
    Be very careful when using exec/eval, you should never pass any user input to these functions – Iain Shelvington Sep 08 '19 at 02:22
  • @martineau That works. I've never used ```eval()``` before. Thanks! – LogicalX Sep 08 '19 at 02:23

1 Answers1

0

The code is working as expected. The documentation for exec clearly states:

The return value is None.

You might want to use eval:

The return value is the result of the evaluated expression.

However, for both exec and eval, you should make 150% sure that you only process trusted and safe input. In general, it would be much better to parse and evaluate the expression yourself.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653