Elif-row without else python

17,114

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
Share:
17,114
Nearoo
Author by

Nearoo

CS Student @ ETH Zürich

Updated on June 04, 2022

Comments

  • Nearoo
    Nearoo almost 2 years

    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.)

  • jonrsharpe
    jonrsharpe almost 10 years
    At least use a boolean for key1!
  • Nearoo
    Nearoo almost 10 years
    Thanks for the idea - but I my statements aren't always 5... :/
  • jonrsharpe
    jonrsharpe almost 10 years
    @user3424423 perhaps you should have used a clearer example. Nonetheless, any can be used.
  • Nearoo
    Nearoo almost 10 years
    Thanks 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
    Nearoo almost 10 years
    Yeah. I'll remember that. Thanks.