Python Practice › If-Else Programs › Program 1
Check if a number is divisible by 3
Write a Python program to check whether a given number is divisible by 3.
Input
21, 22
Output
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")Output
21 is divisible by 3 22 is not divisible by 3
Line by line
Line 1
The loop tests two sample numbers so both branches run.
Line 2
% gives the remainder; a remainder of 0 means an exact division.
Lines 4-5
else handles every other case.
Learn the concept
New to this topic? Read the lesson, then come back.