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.
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.")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With