# How to check if a number is a perfect square in Python

In this article, we will learn to check if a number is a perfect square in python

Given below is the Python code to check if a number is a perfect square or not. The logic behind the code is that we are finding the square root of a number using the math.sqrt() function. Next, we check if the square root we obtained is an integer or not. If an integer, then the given number is a Perfect Square, else it is not.

import math def perfectSquarCheck(x): # find floating point value of # square root of x. sr = math.sqrt(x) # If square root is an integer return ((sr - math.floor(sr)) == 0) nums = [4, 8, 16, 25, 100, 2500, 3225, 5000] for i in nums: if (perfectSquarCheck(i)): print(i, " is a Perfect Square") else: print(i, " is not a Perfect Square")

Output:

4 is a Perfect Square 8 is not a Perfect Square 16 is a Perfect Square 25 is a Perfect Square 100 is a Perfect Square 2500 is a Perfect Square 3225 is not a Perfect Square 5000 is not a Perfect Square

Subscribe

Login

Please login to comment

0 Discussion