Python if / elif条件

时间:2016-08-01 21:01:59

标签: python

有没有办法在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

我要做的是避免在z = x + y等中明确重写elif == 2因为我的应用程序需要执行数百行代码(不像这个简单的例子)。我想我可以将这些东西包裹起来并调用它们,但是我想知道是否有更简洁,更pythonic的方法。

编辑:这里的回答似乎集中在代码的if / elif部分。我认为这是我的错,因为我不能清楚地解释它。如果i == 2,我想执行i == 2的所有代码,除了执行i == 1的代码。我明白我可以把i == 1下的东西放到i == 2条件,但由于它已经存在,有没有办法调用它而不重写它?

3 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:1)

如果条件通过,它将如何工作。否则if仅在先前的if / elif语句条件都没有通过时执行。所以你想要所有if语句不是elif语句

for

答案 2 :(得分:1)

也许是这样的:

if i in (1, 2, 3):
    z = x + y
if i in (2, 3):
    r = x^3 - y
if i == 3:
    s = i^3 + y^2

如果案例很多,您可以用range(...)替换元组。