Check if a number is the cube of 3

EasyIf-Else Programs · 42 of 64

Write a Python program to check whether a number is the cube of 3, and in general whether it is a perfect cube.

Advertisement
Input
27, 28
Output
27 cube of 3: True | perfect cube: True
28 cube of 3: False | perfect cube: False

Approach

  1. Compare with 3 ** 3; for the general test round the cube root and cube it again.

Solution

Python
for n in [27, 28]:    root = round(n ** (1 / 3))    print(n, "cube of 3:", n == 3 ** 3, "| perfect cube:", root ** 3 == n)
Output
27 cube of 3: True | perfect cube: True
28 cube of 3: False | perfect cube: False

Line by line

Line 2

n ** (1/3) is a float cube root such as 3.0000000000000004, so it is rounded before checking.

Advertisement

Learn the concept

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

More if-else programs

← All 64 If-Else Programs