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
>>>
4
solved Python 3 – exec() Vs eval() – Expression evaluation [duplicate]