没有其他Python的Elif-row [英] Elif-row without else python
问题描述
是否可以在 if
行的末尾编写 else
,只有在所有 if
语句都没有的情况下才执行是真的吗示例:
Is it possible to write an else
at the end of an if
-row which only gets executed if none of all the if
statements are true? Example:
if foo==5:
pass
if bar==5:
pass
if foobar==5:
pass
else:
pass
在此示例中,如果 foobar
不是5,则执行else部分,但如果 foo
, bar
和 foobar
都不是5.(但是,如果所有语句为true,则必须执行所有语句.)
In this example, the else part gets executed if foobar
isn't 5, but I want it to be executed if foo
, bar
and foobar
aren't 5. (But, if all statements are true, all of them have to be executed.)
推荐答案
我认为在Python或任何其他语言中,没有任何过分优雅的方式可以做到这一点.您可以将值存储在列表中,但会混淆实际的测试条件,例如
I don't think there's any overly elegant way to do this in Python or any other language. You could store the values in a list but that would obfuscate the actual test ifs, e.g.
tests = [bar ==4, foo == 6, foobar == 8]
if tests[0] :
# do a thing
if tests[1] :
# Make a happy cheesecake
if tests[2] :
# Oh, that's sad
if not True in tests :
# Invade Paris
或者您可以设置跟踪标记
Or you could set a tracking flag
wereAnyTrue = False
if foo == 4 :
# Do the washing
wereAnyTrue = True
if bar == 6 :
# Buy flowers for girlfriend
wereAnyTrue = True
# ... etc
if not wereAnyTrue :
# Eat pizza in underpants
这篇关于没有其他Python的Elif-row的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!