In this article, we’ll explore how to write a Python program to determine whether a given number is a perfect square. This exercise will help you understand mathematical operations and conditional logic in Python.
A Perfect Square is a number that can be expressed as the square of an integer. In other words, if you multiply an integer by itself, the result is called a Perfect Square. For example, 4=2×2, so 4 is a perfect square. Similarly, 9=3×3, so 9 is a perfect square. And so on…
This tutorial covers various methods to check if a number is a perfect square in Python, with explanations and examples.
1. How to check if Number is Perfect Square in Python
Steps to check if a number is a Perfect Square
- Set Number
Set number or take an integer
numberas input from the user. - Handle Negative and Zero Cases:
If the number is negative, it cannot be a perfect square. Return
False.
If the number is 0, it is a perfect square (0 * 0 = 0). ReturnTrue.
Ensure the number is non-negative because negative numbers cannot be perfect squares. - Calculate Square Root
Use
math.sqrt(num)to compute the square root of the number. For Example, math.sqrt(16) = 4.0 - Check if the Square Root is an Integer
Determine if the calculated square root is an integer. If the square root is an integer, the original number is a perfect square. Use the
is_integer()method to verify if the square root is a whole number.
For example,math.sqrt(15) = 3.872983346207417returnsFalse, whereas math.sqrt(16) = 4.0 returns True. - Return the result
Return
Trueif the square root is an integer, andFalseotherwise.
Code Example
2. Using math.isqrt function
math.isqrt() is a function in Python’s math module that computes the integer square root of a non-negative integer. It avoids floating-point precision issues by returning an exact integer.
For Example, a Square root of 15 is 3.872983346207417, but math.isqrt(15) returns 3.
This method uses the math.isqrt() function to calculate the square root of a number and check if the integer square root, when squared, equals the original number to determine if it is a perfect square in Python.
For instance, for num = 25, math.isqrt(25) returns 5. Multiplying 5 * 5 results in 25, validating it as a perfect square.
Code Example
Explanation
math.isqrt(): Computes the integer square root of a number, avoiding potential floating-point precision errors.- Validation check: Compute the integer square root using
math.isqrt()and multiply it by itself. If the result equals the original number, it confirms that the number is a perfect square. math.isqrt()is available from Python 3.8. For earlier versions, useint(math.sqrt(num))
Note:
- Zero is considered a perfect square: 0×0=0
- Negative numbers are never perfect squares because the square of any real number (positive or negative) is non-negative.

Leave a Reply