Check Perfect Square in Python

Check whether a number is a perfect square.

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 = int(math.sqrt(num))
11 if root * root == num:
12 print(num, "is a perfect square")
13 else:
14 print(num, "is not a perfect square")

Output

Enter a non-negative integer: 16
16 is a perfect square

What's going on

We take the integer square root and square it back.

If root * root equals the original number, it is a perfect square.

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.