Numbers from 1 to 30 divisible by 3

EasyIf-Else Programs · 2 of 64

Write a Python program to print all the numbers from 1 to 30 that are divisible by 3.

Advertisement
Output
3 6 9 12 15 18 21 24 27 30 

Approach

  1. Loop from 1 to 30 and print a number only when n % 3 == 0.

Solution 1: loop with if

Python
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

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs