The Python Oracle

if or elif either true then do something

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands

--

Chapters
00:00 If Or Elif Either True Then Do Something
00:26 Answer 1 Score 19
00:54 Answer 2 Score 6
01:13 Answer 3 Score 7
01:32 Answer 4 Score 35
01:52 Thank you

--

Full question
https://stackoverflow.com/questions/2175...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27

#avk47



ANSWER 1

Score 35


You could also omit the either_true flag completely if doSomething3 is a single line of code (e.g. a function call):

if x:
  ..do something 1
  ..do something 3
elif y:
  ..do something 2
  ..do something 3

It maintains the nice property of evaluating x and y at most once (and y won't be evaluated if x is true).




ANSWER 2

Score 19


I would handle this by using nested if statements i.e.

if x or y:
    if x:
        ...do something1
    elif y:
        ...do something2
    ...do something3

As some comments have pointed out, the best solution will depend on what x & y are. If easy readability / concise code is your goal then this or other answers given should be fine. If however x & y were expensive function calls then it would be better to do something more like what you have done to avoid calling the function twice.




ANSWER 3

Score 7


You could wrap some of it in a function:

def do_stuff():
    if x:
        ...do something1
        return True
    elif y:
        ...do something2
        return True
    else:
        return False

if do_stuff():
    ..do something3

Or all of it in a function:

def do_stuff()
    if x:
        ...do something1
    elif y:
        ...do something2
    else:
        return

    ..do something3



ANSWER 4

Score 6


if x or y:
    dosomethig1() if x else dosomething2()
    dosomething3()

Of course, this does evaluate x.__nonzero__ twice. Usually that's not a big deal, but if it is expensive, you can always evaluate that upfront and save it to a temporary variable.