Square or cube depending on divisibility

EasyIf-Else Programs · 11 of 64

Write a Python program that prints the square of a number if it is divisible by 2, or its cube if it is divisible by 3.

Advertisement
Input
4, 9, 6, 7
Output
4 square: 16
9 cube: 729
6 square: 36
7 is divisible by neither 2 nor 3

Approach

  1. Check divisibility by 2 first, then by 3.

Solution

Python
for n in [4, 9, 6, 7]:    if n % 2 == 0:        print(n, "square:", n ** 2)    elif n % 3 == 0:        print(n, "cube:", n ** 3)    else:        print(n, "is divisible by neither 2 nor 3")
Output
4 square: 16
9 cube: 729
6 square: 36
7 is divisible by neither 2 nor 3

Line by line

Lines 2-5

6 is divisible by both; because the % 2 test comes first, it prints the square.

Tip

To print both for numbers like 6, use two separate if statements instead of if / elif.

Advertisement

Learn the concept

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

More if-else programs

← All 64 If-Else Programs