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?
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?
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.