Search code examples
pythonif-statementintegermodulo

Python, using the modulo operator with nested if statements to find if the int 'x' is divisible by 3 and 5


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.


Solution

  • 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.