带有 if 语句的 python exec()

标签 python python-3.x

我正在尝试找到一种方法来执行 if 语句。

所以,例如:

exampleCode = "if 0 < 1:"

exec(exampleCode)
    print("Zero is less than one")

现在,显然这对于​​ exec() 是不可能的。但它有类似的东西吗?

其他可行的方法是:

exampleCode = "if 0 < 1:"

exampleCode
    print("Zero is less than one")

同样,这是不可能的,因为变量不能是代码。

那么,还有什么其他可能有用的东西吗?

最佳答案

你可以用 eval 来做到这一点:

exampleCode = "0 < 1"
if eval(exampleCode):
    print("Zero is less than one")

...但不清楚这样做的好处是什么(也就是说,您没有向我们展示某些东西来激发您的问题)。

关于带有 if 语句的 python exec(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30857810/

相关文章:

python - 按下登录按钮后,如何获取Tkinter条目的值并将其传递给SQL查询?

python-3.x - 需要找到完全匹配并使用正则表达式替换

python - 在哪里可以查看内置 Python 方法 id() (Python 3.x) 的代码?

python - 如何在 Colaboratory Google 上使用 Selenium?

python - 从列表中获取素数

python - 是否有自动将字符串格式类型转换为 f 字符串的工具?

python - LayerNorm inside nn.Sequential in torch

python - pygame.错误 : No available video device

python - 如何使 python 脚本在 Windows 上可执行?

python - 如何在满足特定的 "for loop"条件时跳过一轮 "if"继续下一轮?