What are valid statements inside a python eval()?

邮差的信 提交于 2020-01-13 10:55:10

问题


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


回答1:


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.




回答2:


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!


来源:https://stackoverflow.com/questions/13851389/what-are-valid-statements-inside-a-python-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!