Skip to main content

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

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

Here's a step-by-step tutorial on how to check if a number is a perfect square in Python:

Step 1: Start by defining a function named is_perfect_square that takes a single parameter, num, representing the number to be checked.

Step 2: Inside the function, check if the square root of the number is an integer. You can do this by comparing the square root of num with its integer equivalent using the == operator.

Here's an example code snippet for step 2:

def is_perfect_square(num):
if num**0.5 == int(num**0.5):
return True
else:
return False

Step 3: Test the function by calling it with different numbers and printing the result. For example:

print(is_perfect_square(16))  # Output: True
print(is_perfect_square(25)) # Output: True
print(is_perfect_square(31)) # Output: False

Step 4: If the function returns True, it means the number is a perfect square. Otherwise, it is not.

That's it! You have successfully checked if a number is a perfect square using Python.