# Python Program To Check If A Number Is Perfect Square

Any number which can be expressed as the product of two whole equal numbers is classified as a perfect square. For example, 64 can be written as 8*8 hence 64 is a perfect square.

In this article, we will create a Python program to check whether the number is a perfect square or not.

## Algorithm To Check If A Number Is A Perfect Square Or Not

Step 1:  Take the input from the user

Step 2:  Compute the square root of the given number using the math library

Step 3: Checking whether the  int(root + 0.5) ** 2 == number, if this evaluates to True then the number is a perfect square

## Python Program To Check If A Number Is A Perfect Square

``````import math

# Taking the input from user
number = int(input("Enter the Number"))

root = math.sqrt(number)
if int(root + 0.5) ** 2 == number:
print(number, "is a perfect square")
else:
print(number, "is not a perfect square")``````

## Explanation

First, we are importing the math library in our program then we are taking the input from the user and converting it to integer just in case user inputs a float number.

Square root of the number is calculated with  `math.sqrt` method and the result is stored in  `root` variable. Next, we are checking whether the integer value of the square of `root+0.5` is equal to the number itself if this evaluates to True, then the number is a perfect square else it is not.

Notice we are adding 0.5 to the root because in case of a large number the root may not be a perfectly whole number it might be some decimal less. However, as it is known the `int()` method takes the floor value adding 0.5 to the float number is a reliable solution to get the desired outputs even if the input is large.

Running the program for some test cases gave the following output,

``````Enter the Number 444
444 is not a perfect square

Enter the Number 64
64 is a perfect square

Enter the Number 81
81 is a perfect square

Enter the Number 998001
998001 is a perfect square``````

### One Comment

1. py_fido says:

Thanks for this solution. it was very helpful.
However in your explanation; int() does not take the floor value of a number instead it truncates it
i.e int() behaves like math.trunc() as opposed to math.floor() this is very clear when we put a number like -2.5 into each function and observe their outputs.

Thanks for post, again.