Check if a number is divisible by 3
Write a Python program to check whether a given number is divisible by 3.
21, 22
21 is divisible by 3 22 is not divisible by 3
Approach
- A number is divisible by 3 when the remainder
n % 3is 0.
Solution
for n in [21, 22]: if n % 3 == 0: print(n, "is divisible by 3") else: print(n, "is not divisible by 3")21 is divisible by 3 22 is not divisible by 3
Line by line
The loop tests two sample numbers so both branches run.
% gives the remainder; a remainder of 0 means an exact division.
else handles every other case.
Learn the concept
New to this topic? Read the lesson, then come back.