我正在尝试找到一种方法来执行 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/