What are valid statements inside a python eval(

2019-05-06 18:48发布

I have tried

eval('print("hello world")')
eval('return 0')

which are both incorrect. Why are they invalid and what rules should I follow when using eval() (other than as little as possible)?

标签: python eval
2条回答
Ridiculous、
2楼-- · 2019-05-06 19:05

eval() is used to evaluate a value of a varaible as a variable.

example:

var="Hello World!"
code="var"
print eval(code)

output should be:

Hello World!
查看更多
可以哭但决不认输i
3楼-- · 2019-05-06 19:20

In Python, eval() evaluates expressions (something that results in a value). Both print and return are defined as statements (however in Python 3, print is actually a function call, which is an expression). In the case of executing statements, you need to use the exec statement instead.

查看更多
登录 后发表回答