Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Python Program To Check If A Number Is Perfect Square

2 min read

A perfect square is a number that can be expressed as the square of an integer. For example, 4, 9, 16, and 25 are perfect squares because they are equal to 2^2, 3^2, 4^2, and 5^2, respectively.

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

Understanding the Algorithm

To determine if a number is a perfect square, we need to find the square root of the given number and check if the square root is an integer. If the square root is an integer, then the number is a perfect square; otherwise, it is not.

Here is the step-by-step algorithm:

  1. Take the input number from the user.
  2. Calculate the square root of the input number using the math library.
  3. Check if the square root is an integer by comparing it with its integer value (rounded down).
  4. If the square root is equal to its integer value, then the number is a perfect square; otherwise, it is not.

Python Program to Check if a Number is a Perfect Square

import math

def is_perfect_square(num):
    if num < 0:
        return False

    # Calculate the square root
    square_root = math.isqrt(num)

    # Check if the square root is equal to its integer value
    return square_root * square_root == num

# Take input from the user
try:
    number = int(input("Enter a number: "))
    if is_perfect_square(number):
        print(f"{number} is a perfect square.")
    else:
        print(f"{number} is not a perfect square.")
except ValueError:
    print("Invalid input. Please enter a valid integer.")

Explanation of the Code

  1. We import the math module to use the isqrt() function, which calculates the integer square root of a given number.

  2. The is_perfect_square() function takes an integer num as input and returns True if it is a perfect square, otherwise False.

  3. In the is_perfect_square() function, we first check if the input num is less than 0. If it is negative, we immediately return False because negative numbers cannot be perfect squares.

  4. Next, we calculate the square root of num using the isqrt() function.

  5. Finally, we check if the square of the calculated square_root is equal to num. If the condition is true, then num is a perfect square, and the function returns True. Otherwise, it returns False.

  6. In the main program, we take user input for the number to be checked. We then call the is_perfect_square() function and print the result accordingly.

Testing the Program

Let's test the program with some sample inputs:

Input

Enter a number: 16

Output

16 is a perfect square.

That's all! The program works as expected and correctly identifies whether a number is a perfect square or not.


PROGRAMS

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read