Input a number and check whether it is divisible by 3, by 5, by both, or by neither
Expt. No.06
Page No.12
Divisibility by 3 and 5
Aim
To write a Python program that checks whether a number is divisible by 3, by 5, by both or by neither.
Concepts used
Algorithm
- Input a whole number.
- If the remainder on dividing by 3 and by 5 is 0, it is divisible by both.
- Else if only the remainder by 3 is 0, it is divisible by 3.
- Else if only the remainder by 5 is 0, it is divisible by 5.
- Otherwise it is divisible by neither.
Program
# Check divisibility of a number by 3 and by 5 num = int(input("Enter a number: "))if num % 3 == 0 and num % 5 == 0: print(num, "is divisible by both 3 and 5")elif num % 3 == 0: print(num, "is divisible by 3 but not by 5")elif num % 5 == 0: print(num, "is divisible by 5 but not by 3")else: print(num, "is divisible by neither 3 nor 5")
A marked line continues the line above it. In your file, write it on the same line.
Output
Run 1
$ python divisibility_by_3_and_5.py
Enter a number: 45
45 is divisible by both 3 and 5
Run 2
$ python divisibility_by_3_and_5.py
Enter a number: 27
27 is divisible by 3 but not by 5
Run 3
$ python divisibility_by_3_and_5.py
Enter a number: 14
14 is divisible by neither 3 nor 5
✓ Printed by running this program, not typed by hand.
Result
45 was reported as divisible by both 3 and 5, 27 by 3 only, and 14 by neither, matching the remainders 45 % 15 = 0, 27 % 3 = 0 and 14 % 3 = 2, 14 % 5 = 4.
Viva voce: what the examiner may ask
01What does the % operator give?
The remainder of a division, e.g. 14 % 5 is 4. A number is divisible when the remainder is 0.
02Why must the "both" condition be checked first?
If num % 3 == 0 came first, 45 would stop there and never reach the "both" message.
03What is the difference between = and ==?
= assigns a value; == compares two values and gives True or False.
Variations for the lab test
- Check divisibility by any two numbers the user enters.
- Print all numbers from 1 to 50 that are divisible by both 3 and 5.
- Use
notto print numbers divisible by neither.
! Common mistake Putting the
and condition last: an if-elif chain stops at the first true condition, so the "both" case is never reached.