Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple Ifs in python that are not mutually exclusive

a=0
while a<30:
    a+=1
    print(a)
    if a%3==0:
        print("This is a multiple of 3.")
    if a%5==0:
        print("This is a multiple of 5.")
    else:
        print("This is not a multiple of 3 or 5.")

I'd like for this else statement to only print if NEITHER of the previous if statements are true. I don't want to use if, elif, else because the variable could be both a multiple of 3 and 5.

like image 249
Katie Hough Avatar asked Dec 11 '22 10:12

Katie Hough


2 Answers

you could set a flag if one of both conditions is matched. If the flag is still False after both tests, print the fallback message:

a=0
while a<30:
    a+=1
    print(a)
    match = False
    if a%3==0:
        print("This is a multiple of 3.")
        match = True
    if a%5==0:
        print("This is a multiple of 5.")
        match = True
    if not match:
        print("This is not a multiple of 3 or 5.") 

this technique also avoids computing modulo of 3 and 5 more than once.

If you want to add more divisors, avoid copy/paste, and consider testing in a loop (BTW why using a while loop when you have for and range ?):

for a in range(1,31):
    print(a)
    match = False
    for i in [3,5]:
        if a%i==0:
            print("This is a multiple of {}.".format(i))
            match = True
    if not match:
        print("This is not a multiple of 3 or 5.")
like image 174
Jean-François Fabre Avatar answered Dec 12 '22 22:12

Jean-François Fabre


Expanding upon my comment:

if not a % 3:
    print("This is a multiple of 3.")

if not a % 5:
    print("This is a multiple of 5.")

if a % 3 and a % 5:
    print("Not a multiple of 3 or 5.")

If a number is divisible, a % x is 0, which is False. We use the truthiness of 0 and 1 to determine the outcome of the conditional.


Slight optimisation:

if not a % 3:
   ...

if not a % 5:
   ...

elif a % 3:
   ...

Condenses the last 3 tests slightly to prevent a redundant test.


In the end, I believe a flag is nicer, because you perform your arithmetic operations one time less.

like image 30
cs95 Avatar answered Dec 13 '22 00:12

cs95