Python Practice › If-Else Programs › Program 4
Check divisibility by 3 and 5
Write a Python program to check whether a number is divisible by both 3 and 5.
Input
45, 30, 9, 10
Output
45 is divisible by 3 and 5 30 is divisible by 3 and 5 9 is divisible by 3 only 10 is divisible by 5 only
Approach
- Combine the two remainder checks with
and.
Solution
for n in [45, 30, 9, 10]: if n % 3 == 0 and n % 5 == 0: print(n, "is divisible by 3 and 5") elif n % 3 == 0: print(n, "is divisible by 3 only") elif n % 5 == 0: print(n, "is divisible by 5 only")Output
45 is divisible by 3 and 5 30 is divisible by 3 and 5 9 is divisible by 3 only 10 is divisible by 5 only
Line by line
Line 2
and is true only when both conditions are true; this test must come first.
Lines 4-7
The other branches report partial matches.
Learn the concept
New to this topic? Read the lesson, then come back.