Skip to content Skip to sidebar Skip to footer

Python 3 - Exec() Vs Eval() - Expression Evaluation

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

Solution 1:

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 1for i inrange(1, 11): print(i)
      ^
SyntaxError: invalid syntax
>>> exec('for i in range(1, 11): print(i)')
12345678910>>> 

Post a Comment for "Python 3 - Exec() Vs Eval() - Expression Evaluation"