Elif-row without else python
Solution 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
Solution 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
Solution 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)):
...
Solution 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
Comments
-
Nearoo almost 2 years
Is it possible to write an
else
at the end of anif
-row which only gets executed if none of all theif
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 iffoo
,bar
andfoobar
aren't 5. (But, if all statements are true, all of them have to be executed.) -
jonrsharpe almost 10 yearsAt least use a boolean for
key1
! -
Nearoo almost 10 yearsThanks for the idea - but I my statements aren't always 5... :/
-
jonrsharpe almost 10 years@user3424423 perhaps you should have used a clearer example. Nonetheless,
any
can be used. -
Nearoo almost 10 yearsThanks for your answer, I will use this solution since I'm able to find out wheter something was
true
or not anyways. I just thought - maybe python has it's own, easier way of doing it... :) -
Nearoo almost 10 yearsYeah. I'll remember that. Thanks.