问题
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
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.)
回答1:
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
回答2:
How about doing something like this? Making four if statements but the fourth if statement won't be run if one of the other three is run because the other statements change the variable 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:
Not directly - those three if
blocks are separate. You could use nesting, but that would get pretty complex; the neatest way to accomplish this is probably:
if foo == 5:
...
if bar == 5:
...
if foobar == 5:
...
if not any((foo == 5, bar == 5, foobar == 5)):
...
回答4:
If all the if
statements are for checking for the same value, I would use the following format instead. It would make the code shorter and more readable, IMO
if 5 in (foo, bar, foobar):
pass
else:
pass
回答5:
A variation of jonrsharpe's answer would be using chained equality tests. Like so:
if foo != bar != foobar != 5:
#gets executed if foo, bar and foobar are all not equal to 5
Looks a bit funny, I guess it's up to you to decide which one is more readable. And, obviously, this won't work if one of those variables is supposed to be equal to something different.
Edit: whoops, this won't work. For example
1 != 1 != 3 != 5
returns false, while
1 != 2 != 3 != 5
return true. Sorry
来源:https://stackoverflow.com/questions/24230930/elif-row-without-else-python