Skip to main content
 首页 » 编程设计

带有 if 语句的 python exec()

2025年05月04日13arxive

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

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