I want to write a programme that calculates wheather the number is divisible by 5 ,7 or not. If the number is divisible by 5 or 7 the outpt will be the print statement otherwise the expect statement, but in my code if the number is not divisible by any of 5 or 7 then it stucks there.How to fix this? Here is the code:-
number = int(input("Enter an integer: "))
while True:
try:
if number % 5 == 0:
print("divisible by 5")
break
if number % 7 == 0:
print("divisible by 7")
break
except:
print("number is not divisible by 5 or 7")
CodePudding user response:
The except statement will never be triggered as you do not throw any errors. You can just add the print statement at the bottom of the other if statements.
number = int(input("Enter an integer: "))
if number % 5 == 0: print("divisible by 5")
elif number % 7 == 0: print("divisible by 7")
else: print("number is not divisible by 5 or 7")
CodePudding user response:
Well assuming that you have added the while loop for repeated user input you can try something like this...
while True:
number = int(input("Enter an integer: "))
try:
if number % 5 == 0:
print("divisible by 5")
break
elif number % 7 == 0:
print("divisible by 7")
break
else:
raise Exception
except Exception as exception:
print("number is not divisible by 5 or 7")
continue
You can check this also...
number = int(input("Enter an integer: "))
print("divisible by ", number) if number % 5 == 0 or number % 7 == 0 else print("number is not divisible by 5 or 7")