Python 3 - exec() Vs eval() - Expr

2019-09-29 04:35发布

This question already has an answer here:

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() ?

标签: python
1条回答
Emotional °昔
2楼-- · 2019-09-29 05:07

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
>>> 
查看更多
登录 后发表回答