In this post, we will learn how to check if a number is a perfect square in Python with a very simple example and algorithm, but before we jump into the programming part, let’s see what is a perfect square.

What is a Perfect Square?

A positive integer that is multiplied by itself and the resultant product is known as a perfect square.

For Example:

Examples of Perfect Square in python

Algorithm for Perfect Square

  1. Take input from a user (num).
  2. Create one variable called flag and initially set it to zero (flag = 0).
  3. iterate through the loop from 1 to num (for i in range(1, num+1)).
  4. inside the loop check if i*i == num then do step-5
  5. increase the flag by 1 (flag = 1) and break the loop
  6. Outside the loop check if flag == 1 then print number is a perfect square.
  7. else print number is not a perfect square

With the help of this algorithm, we will write the Python program to check if the number is a perfect square or not, but before writing this program few programming concepts you have to know:

  1. how to take input from the user
  2. for-loop &
  3. if-else

Source Code

num = int(input("Enter a Number: "))
flag = 0

for i in range(1, num+1):
    if i*i == num:
        flag = 1
        break

if flag == 1:
    print(f"{num} is a Perfect Square")
else:
    print(f"{num} is not a Perfect Square")

Output

Enter a Number: 9
9 is a Perfect Square

You can also use the sqrt() function from the math module to write this program. Let’s see how.

Python program to check if the number is a perfect square or not using the sqrt() function

Before writing this program you should know about:

  1. math module (sqrt() function) &
  2. if-else

Source Code

import math
my_num = int(input("Enter A Number: "))
sq_root = int(math.sqrt(my_num))

if sq_root* sq_root == my_num:
    print(f"{my_num} is a Perfect Square")
else:
    print(f"{my_num} is not a Perfect Square")

Output

Enter A Number: 100
100 is a Perfect Square
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment