复合如果elif else语句+ python

时间:2015-02-10 22:33:07

标签: python

我正在尝试从复合/嵌套if / elif / else语句中传递一个项目。

if x == 0:
    do something
elif x == 1:
    do something else
elif x == 2:
    if x == 2 and x == whatever:
        do something
    elif x == 2 and x == whatever:
        do something
    else:
        pass it back out
elif x = 3:
    do something
else:
    do something

如果能检查它是否等于3,我怎样才能将它传回内部?

传递语句在这里工作吗?继续不断抛出错误。

3 个答案:

答案 0 :(得分:3)

if x == 0:
    do something
elif x == 1:
    do something else
elif x == 2 and y == whatever:
        do something
elif x == 2 and y == whatever:
        do something

elif x = 3:
    do something
else:
    do something

可能?如果您已输入一个

,则无法输入新的if / elif分支

另一种选择是将其余内容移到

if x == 0:
    do something
elif x == 1:
    do something else
elif x >= 2:
    if x == 2 and x == whatever:
        do something
    elif x == 2 and x == whatever:
        do something
    elif x = 3:
        do something
    else:
        do something

另一个选择是遵循其他示例并启动一个新的if块,尽管您需要小心不要检查其他分支之一可能会发生变化的条件......并且每个选项必须互相排斥其他选项

答案 1 :(得分:0)

您确实不需要elif语句,因为您需要检查每个语句中x的值。将它们全部更改为if语句,并将最终的else语句更改为if x > 3:

答案 2 :(得分:0)

您希望将其传递出去,但使用if语句而不是elif。

else:
    pass it back out
if x  == 3