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!

2 Answers 2

4

This might help.

setExp3 = True
if cond1:
    expr1
    if cond2:
        expr2
        setExp3 = False

if setExp3:
    expr3
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

Comments

Your Answer

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.