how should the following code be structured in order for the correct statements to be printed when the user has input an integer?
What am i doing wrong? i have tried to change the code in so many ways with no luck.
x = int(input("Please enter a number:\n"))
if x % 3 == 0 and x % 5 == 0:
print("Your number is divisible by 3 and 5.")
if x % 3 == 0 and x % 5 == 1:
print("Your number is divisible by 3 and NOT 5.")
elif x % 3 == 1 and x % 5 == 0:
print("Your number is NOT divisible by 3 and is divisible by 5.")
else:
print("Your number is NOT divisible by 3 and 5.")
or
x = int(input("Please enter a number:\n"))
if ((x % 3 == 0) & (x % 5 == 0)):
print("Your number is divisible by 3 and 5.")
if ((x % 3 == 0) & (x % 5 == 1)):
print("Your number is divisible by 3 and NOT 5.")
elif ((x % 3 == 1) & (x % 5 == 0)):
print("Your number is NOT divisible by 3 and is divisible by 5.")
else:
print("Your number is NOT divisible by 3 and 5.")
I want the correct phrase to be displayed once the user has input their chosen integer.
CodePudding user response:
Each time you think you're checking for "not divisible by a number", you're actually checking "exactly one greater than a multiple of that number". The test shouldn't be == 1
, it should be != 0
to cover when the remainder is anything but zero (a number that is not divisible by 3
might have remainders of 1
or 2
, a number not divisible by 5
might have remainders of 1
, 2
, 3
or 4
; you just care if the remainder is 0
or "something else", not 1
specifically).
You also over-indented two of your tests (so they'd only get tested when x % 3 == 0 and x % 5 == 0
, and the tests were guaranteed to fail). Fixed code:
x = int(input("Please enter a number:\n"))
if x % 3 == 0 and x % 5 == 0:
print("Your number is divisible by 3 and 5.")
elif x % 3 == 0 and x % 5 != 0: # Changed % 5 test, dedented and made elif
print("Your number is divisible by 3 and NOT 5.")
elif x % 3 != 0 and x % 5 == 0: # Changed % 3 test and dedented
print("Your number is NOT divisible by 3 and is divisible by 5.")
else:
print("Your number is NOT divisible by 3 and 5.")
It's possible to simplify further (so you don't recompute x % 3
and x % 5
up to three times each), and Byron's answer provides a good example of that, but I left this as close to your original code as possible to demonstrate the minimal fixes (though I did PEP8-ify your indentation levels to make them easier to read: The One True Indentation is four spaces per level).
CodePudding user response:
Awful shorthand but here:
if x % 3 == 0:
if x % 5 == 0:
print("Your number is divisible by 3 & 5")
else:
print("Your number is divisible by 3 and NOT 5.")
elif x % 5 == 0:
print("Your number is NOT divisible by 3 and is divisible by 5.")
else:
print("Your number is NOT divisible by 3 and 5.")
Also, your check where you do "x % 3 == 1" doesn't make a whole lot of sense because x % 3 could also be 2, in which case the branch wouldn't get hit.