jeudi 5 septembre 2019

Nested if statements with same else expressions in python

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!

Aucun commentaire:

Enregistrer un commentaire