Python中没有else的elif行
可以在一个if
语句的最后加一个else
吗?这个else
只有在所有的if
条件都不成立时才会执行?举个例子:
if foo==5:
pass
if bar==5:
pass
if foobar==5:
pass
else:
pass
在这个例子中,else
部分会在foobar
不等于5时执行,但我希望它在foo
、bar
和foobar
都不等于5时执行。(不过,如果所有的条件都成立,那所有的部分都得执行。)
5 个回答
0
一种变体是使用连锁的相等测试。就像这样:
if foo != bar != foobar != 5:
#gets executed if foo, bar and foobar are all not equal to 5
看起来有点奇怪,我想这要看你自己觉得哪个更容易读懂。当然,如果其中一个变量应该等于其他不同的东西,这种写法就不适用了。
编辑:哎呀,这个方法不行。比如说
1 != 1 != 3 != 5
会返回假,而
1 != 2 != 3 != 5
会返回真。抱歉!
1
如果所有的if
语句都是在检查同一个值,我会用下面这种格式。这样可以让代码更简洁,也更容易读懂,我觉得这样更好。
if 5 in (foo, bar, foobar):
pass
else:
pass
2
这三个 if
语句是独立的,不能直接连接在一起。你可以使用嵌套的方式来实现,但那样会变得比较复杂。最简单明了的做法可能是:
if foo == 5:
...
if bar == 5:
...
if foobar == 5:
...
if not any((foo == 5, bar == 5, foobar == 5)):
...
5
你觉得这样做怎么样?可以写四个if语句,但如果前三个if语句中的任何一个被执行了,第四个if语句就不会再执行,因为前三个语句会改变变量key
的值。
key = True
if foo == 5:
key = False
if bar == 5:
key = False
if foobar == 5:
key = False
if key:
pass # this would then be your else statement
3
我觉得在Python或者其他语言中,没什么特别优雅的方法来做到这一点。你可以把这些值放在一个列表里,但这样会让实际的测试条件变得不清晰,比如:
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
或者你可以设置一个跟踪标志
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