I am wondering whether there is a nice solution in python for nested if statements where all else have the same expression, without having to rewrite that expression?
In the example below I rewrite expr3 for both else statements:
if cond1:
expr1
if cond2:
expr2
else:
expr3
else:
expr3
The issue above is that expr1 is conditional on cond1, but not cond2. Unless there is something like an "all else" expression, the only simplification I see at the moment, is to break it into two statements:
if cond1 and cond2:
expr2
else:
expr3
and
if cond1:
expr1
Would be glad to see any other suggestions!
2 Answers 2
This might help.
setExp3 = True
if cond1:
expr1
if cond2:
expr2
setExp3 = False
if setExp3:
expr3
answered Sep 5, 2019 at 9:45
Rakesh
82.9k17 gold badges86 silver badges122 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
user3485516
Using a boolean
setExp could be useful to shorten the code!I'd rather do it differently:
if cond1 :
expr1
if cond2 :
expr2
if not (cond1 and cond2) :
expr3
answered Sep 5, 2019 at 9:55
lenik
23.6k4 gold badges38 silver badges44 bronze badges
Comments
lang-py