Editor

Python Program to Check if a Number Is a Perfect Square

Beginner · Numbers

A perfect square is a whole number that is the square of another whole number, like 49 = 7 x 7 or 144 = 12 x 12. This program checks whether a number is a perfect square using the whole-number part of its square root.

Program

perfect_square.py
import math
num = 144 # or: num = int(input("Enter a number: "))
if num < 0:
print(num, "is negative, so it is not a perfect square")
else:
root = math.isqrt(num) # whole-number square root, rounded down
if root * root == num:
print(f"{num} is a perfect square: {root} x {root} = {num}")
else:
print(f"{num} is not a perfect square")
print(f"It lies between {root * root} and {(root + 1) ** 2}")
Output
144 is a perfect square: 12 x 12 = 144

How it works

  1. math.isqrt() gives the square root rounded down to a whole number: 12 for 144, and 12 for 150 as well.
  2. Squaring that root again gives back the number only when the number is a perfect square.
  3. For other numbers the program shows the perfect squares on either side, like 144 and 169 for 150.
  4. math.isqrt() works only with whole numbers, so it is exact even for huge numbers, where decimal square roots can be rounded wrongly.

Other ways to write it

Using math.sqrt() and is_integer()

Using math.sqrt() and is_integer()
import math
for num in [16, 20, 81, 99, 100]:
root = math.sqrt(num)
if root.is_integer():
print(num, "is a perfect square of", int(root))
else:
print(num, "is not a perfect square")
Output
16 is a perfect square of 4
20 is not a perfect square
81 is a perfect square of 9
99 is not a perfect square
100 is a perfect square of 10

This is the common textbook method, and it is fine for ordinary numbers; is_integer() checks that the decimal root has nothing after the point.

Perfect squares in a range

Perfect squares in a range
start, end = 1, 100
squares = []
i = 1
while i * i <= end:
if i * i >= start:
squares.append(i * i)
i += 1
print(f"Perfect squares from {start} to {end}: {squares}")
Output
Perfect squares from 1 to 100: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Instead of testing every number, this squares 1, 2, 3 and so on until the square passes the end, which is much quicker.

Try it yourself

Change the program to also say whether the number is a perfect cube, like 27 or 64.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises