python eval()中的有效语句是什么? [英] What are valid statements inside a python eval()?

查看:110
本文介绍了python eval()中的有效语句是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过

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

这两个都不正确.为什么它们无效?使用eval()时应遵循哪些规则(尽可能少使用)?

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()评估表达式(会产生值的东西). printreturn都定义为语句(但是在Python 3中,print实际上是一个函数调用,它是一个表达式).对于执行语句,您需要使用 exec声明.

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.

这篇关于python eval()中的有效语句是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆