Founding Batch Offer · HLD · LLD · System Design at ₹799 until 30 Nov

Check Perfect Square in Python

Use an exact Python integer square root to test perfect squares. Beginners compare the squared candidate with the input without introducing float rounding.

BeginnerConditional ProgramsExample 7 of 20
check-perfect-square.py
1# Program to check if a number is a perfect square
2
3import math
4
5num = int(input("Enter a non-negative integer: "))
6
7if num < 0:
8 print("Negative numbers cannot be perfect squares in real numbers.")
9else:
10 root = math.isqrt(num)
11 if root * root == num:
12 print(num, "is a perfect square")
13 else:
14 print(num, "is not a perfect square")

Output

16 is a perfect square

isqrt(16) is 4, and 4 * 4 equals 16 exactly.

In this one

  • Use exact integer square roots
  • Verify a candidate by squaring it
  • Avoid float conversion for integer properties

How it works

  1. 1

    Import math and read integer num.

  2. 2

    Reject negatives, otherwise compute root = math.isqrt(num).

  3. 3

    Compare root * root with num and print whether it matches.

Edge cases

Zero

Enter 0.

isqrt returns zero, and zero squared matches the input.

Between squares

Enter 18.

The candidate root is 4, but 16 does not equal 18.

What's going on

A perfect square is an integer formed by squaring another integer. 16 qualifies because 4 * 4 is 16; 18 does not because no integer squared gives 18.

math.isqrt gives the integer square root of a non-negative integer. It is the largest integer whose square is not greater than num. The second test squares this candidate back and requires exact equality.

Unlike converting math.sqrt to int, isqrt does not pass through a float, so large integer squares do not lose precision during the root calculation. The negative guard runs first because isqrt rejects negative arguments. Zero is accepted: its integer root is zero and squaring it gives zero.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why square the candidate root again?

Pick an answer to check it.

Question 2

Why prefer isqrt for large integers?

Pick an answer to check it.

Questions people ask

Why square the candidate root again?

isqrt rounds down for nonsquares, so equality is needed to prove an exact square.

Why prefer isqrt for large integers?

It works with integers directly and avoids floating-point root rounding.

What version of Python provides math.isqrt?

math.isqrt is available in Python 3.8 and later.