Numbers from 1 to 30 divisible by 3

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.

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.

Learn the concept

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

More if-else programs

← All 64 If-Else Programs

Check if a number is divisible by 3

Check if a number is divisible by 3

EasyIf-Else Programs · 1 of 64

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

  1. A number is divisible by 3 when the remainder n % 3 is 0.

Solution

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

More if-else programs

← All 64 If-Else Programs

Python If-Else Programs with Solutions

Python Practice › If-Else Programs

Python If-Else Programs with Solutions

64 programs59 easy5 medium0 hard

64 if-else programs that practise decisions in Python: comparisons, elif chains, nested conditions and combining tests with and / or. Each solution tests several inputs so you can see every branch run.

Before you start

Read the If…Else and Match Case lesson first if the topic is new to you.

All programs