Python Practice › If-Else Programs › Program 41
Check if a number is the square of 6
Write a Python program to check whether a number is the square of 6, and in general whether it is a perfect square.
Input
37, 36
Output
37 square of 6: False | perfect square: False 36 square of 6: True | perfect square: True
Approach
- Compare with
6 ** 2, and usemath.isqrtfor the general test.
Solution
import math for n in [37, 36]: root = math.isqrt(n) print(n, "square of 6:", n == 6 ** 2, "| perfect square:", root * root == n)Output
37 square of 6: False | perfect square: False 36 square of 6: True | perfect square: True
Line by line
Line 4
isqrt gives the whole-number square root.
Line 5
A number is a perfect square when that root squared gives the number back.
Learn the concept
New to this topic? Read the lesson, then come back.