Skip to main content
 首页 » 编程设计

Python if/elif 条件

2025年05月04日25mq0036

有没有办法在 if/elif 结构中执行代码,以便它计算 elif 之前的所有代码?这是一个例子:

i = 1 # this can be anything depending on what to user chooses 
 
x = 5 
y = 10 
 
if i == 1: 
    z = x + y 
 
elif i == 2: 
    # Here I want to return what would have happened if i == 1, in addition other stuff: 
    r = x^3 - y 
 
elif i == 3: 
    # Again, execute all the stuff that would have happened if i == 1 or == 2, an addition to something new: 
    # execute code for i == 1 and i == 2 as well as: 
    s = i^3 + y^2 

我正在尝试做的是避免在 elif == 2 等中显式重写 z = x + y 因为对于我的应用程序有数百个要执行的代码行(不像这个简单的例子)。我想我可以将这些东西包装在函数中并调用它们,但我想知道是否有更简洁、pythonic 的方式来做这件事。

编辑:此处的响应似乎集中在代码的 if/elif 部分。我认为这是我的错,因为我一定没有解释清楚。如果i == 2,除了执行i == 1的代码外,我还想执行i == 2的所有代码。我明白我可以将i == 1下的东西放入i == 2 有条件的,但是既然已经有了,有没有办法不用重写就可以调用呢?

请您参考如下方法:

试试这个:

i = 1 # this can be anything depending on what to user chooses 
 
x = 5 
y = 10 
 
if i >= 1: 
    z = x + y 
 
if i >= 2: 
    # Here I want to return what would have happened if i == 1, in addition other stuff: 
    r = x^3 - y 
 
if i == 3: 
    # Again, execute all the stuff that would have happened if i == 1 or == 2, an addition to something new: 
    # execute code for i == 1 and i == 2 as well as: 
    s = i^3 + y^2