dimanche 22 novembre 2015

Python 3 else for all previous ifs

Say I have the following Python 3 code:

def foo(number_a, number_b):
    if number_a >= 0:
        print("a is Positive")
    if number_b <= 100:
        print("b is <= 100")
    else:
        print("a is negative and b > 100")

How can I have the else fire if and only if both conditions are false?

I could do something like this:

doElse = True
if condition1:
    doElse = False
    # do something
if condition2:
    doElse = False
    # do something
# condition3...conditionN
if doElse:
    # do the else

But that would require setting the variable, then changing it for every if

Is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire