Python Practice › If-Else Programs › Program 2
Numbers from 1 to 30 divisible by 3
Write a Python program to print all the numbers from 1 to 30 that are divisible by 3.
Output
3 6 9 12 15 18 21 24 27 30
Approach
- Loop from 1 to 30 and print a number only when
n % 3 == 0.
Solution 1: loop with if
for n in range(1, 31): if n % 3 == 0: print(n, end=" ")print()Output
3 6 9 12 15 18 21 24 27 30
Line by line
Line 1
range(1, 31) stops before 31, so 30 is included.
Line 3
end=" " keeps the numbers on one line.
Line 4
An empty print() ends the line.
Solution 2: range with a step
print(list(range(3, 31, 3)))Output
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
Line by line
Line 1
Starting at 3 with a step of 3 produces only multiples of 3, so no if is needed.
Learn the concept
New to this topic? Read the lesson, then come back.