if or elif either true then do something
if or elif either true then do something
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC F Haydns String Quartet No 53 in D
--
Chapters
00:00 Question
00:31 Accepted answer (Score 31)
01:33 Answer 2 (Score 35)
02:02 Answer 3 (Score 19)
02:37 Answer 4 (Score 7)
03:04 Thank you
--
Full question
https://stackoverflow.com/questions/2175...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python2.7
#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.