In Python, you can easily check if a number is a perfect square by taking the square root and checking if the square root is an integer.
a = 49
b = 20
c = 16
def check_perfect_square(num):
return int(num ** (1/2)) == num ** (1/2)
print(check_perfect_square(a))
print(check_perfect_square(b))
print(check_perfect_square(c))
#Output:
True
False
True
When working with numbers in Python, the ability to check certain properties of those numbers can be very useful.
One such property is if a number is a perfect square.
A number is said to be a perfect square number if the square root of that number is an integer. Some perfect squares include 1, 4, 9, 16, 25, 36, etc.
To check if a number is a perfect square in Python, you can do the following.
First, find the square root of the given number. Then, you can see if the square root is an integer by comparing the square root to the converted integer value of the square root.
Below is a simple function which will check if a number is a perfect square in Python.
a = 49
b = 20
c = 16
def check_perfect_square(num):
return int(num ** (1/2)) == num ** (1/2)
print(check_perfect_square(a))
print(check_perfect_square(b))
print(check_perfect_square(c))
#Output:
True
False
True
Hopefully this article has been useful for you to learn how to check if a number is a perfect square using Python.
Photo by Kelly Sikkema on Unsplash