-2

After reading query.

below python code is still not clear,

>>> exec('print(5+10)')
15
>>> eval('print(5+10)')
15

In bash world,

exec replace the shell with the given command.

eval execute arguments as a shell command.


Question:

Expression is a computation that evaluates to a value

To evaluate any expression in python(in my case print(5+10) from above python code), How eval() works different from exec() ?

overexchange
  • 15,768
  • 30
  • 152
  • 347

1 Answers1

9

How eval() works different from exec() ?

In your two cases, both eval() and exec() do, do the same things. They print the result of the expression. However, they are still both different.

The eval() function can only execute Python expressions, while the exec() function can execute any valid Python code. This can be seen with a few examples:

>>> eval('1 + 2')
3
>>> exec('1 + 2')
>>> 
>>> eval('for i in range(1, 11): print(i)')
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    eval('for i in range(1, 11): print(i)')
  File "<string>", line 1
    for i in range(1, 11): print(i)
      ^
SyntaxError: invalid syntax
>>> exec('for i in range(1, 11): print(i)')
1
2
3
4
5
6
7
8
9
10
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • 1
    Note that in OP's case, they both print 15 because the `print` function prints whenever it is evaluated. – BallpointBen Jun 22 '17 at 16:02
  • 1
    So, why should I use `eval()` when `exec()` accepts any valid python code? where expressions are part of it. Am not asking whether, `exec()` accepts any python code. – overexchange Jun 22 '17 at 16:03
  • 1
    @overexchange You really shouldn't use _either_ function as they are both dangerous. You could make the case that `eval()` would be _slightly_ less useful because it is only limited to expressions, but you should generally avoid using both, and use an alternative method instead. – Christian Dean Jun 22 '17 at 16:07
  • 1
    @overexchange Look at the example in the answer. If you use `exec()` you don't get the result as a value. `exec('1 + 2')` performs the addition, but there's no way to get the result from it. You would have to do `exec('somevar = 1 + 2')` – Barmar Jun 22 '17 at 16:12