1

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!

asked Sep 5, 2019 at 9:21

2 Answers 2

4

This might help.

setExp3 = True
if cond1:
 expr1
 if cond2:
 expr2
 setExp3 = False
if setExp3:
 expr3
answered Sep 5, 2019 at 9:45
Sign up to request clarification or add additional context in comments.

1 Comment

Using a boolean setExp could be useful to shorten the code!
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.