
Last Updated on 16 March 2025
A perfect square is a number that is the square of an integer. In simple terms, if you can find a whole number that, when multiplied by itself, gives the original number, then it is a perfect square.
Examples of Perfect Squares:
\[ 4=2×2,9=3×3,16=4×4,25=5×5 \]In this tutorial, we will write a Python program to check whether a given number is a perfect square.
Python Program to Check Perfect Square
# Python program to check if a number is a perfect square
import math
# Function to check perfect square
def is_perfect_square(num):
if num < 0:
return False # Negative numbers cannot be perfect squares
sqrt = math.isqrt(num) # Get the integer square root
return sqrt * sqrt == num # Check if square of sqrt equals num
# Taking user input
number = int(input("Enter a number: "))
# Checking and displaying the result
if is_perfect_square(number):
print(f"{number} is a perfect square.")
else:
print(f"{number} is not a perfect square.")
Output
Enter a number: 25 25 is a perfect square.
Using Square Root and Rounding
# Function to check perfect square using square root
def is_perfect_square_alt(num):
if num < 0:
return False
sqrt = num ** 0.5 # Calculate square root
return sqrt == int(sqrt) # Check if it's an integer
# Taking user input
number = int(input("Enter a number: "))
# Checking and displaying the result
if is_perfect_square_alt(number):
print(f"{number} is a perfect square.")
else:
print(f"{number} is not a perfect square.")
This method uses num ** 0.5 to calculate the square root and checks if it is a whole number.