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.

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

Advertisement

Learn the concept

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

More if-else programs

← All 64 If-Else Programs