Exercise 14

Write a Python algorithm that takes an integer input from the user, and checks whether it is a perfect square or not.

Solution

import math

# Take input from the user
n = int(input("Enter a number: "))

# Calculate the square root of the input number
sqrt = math.sqrt(n)

# Check if the square root is an integer
if sqrt.is_integer():
    print(n, "is a perfect square.")
else:
    print(n, "is not a perfect square.")





In this program:

  1. we first imports the math module: to use its sqrt function.
  2. It then takes an integer input: from the user using the input function and converts it to an integer using the int function.
  3. Next, the program calculates the square root: of the input number using the sqrt function from the math module.
  4. If the square root is an integer: it means that the input number is a perfect square, and the program prints a message saying so.
  5. Otherwise, it prints: a message saying that the input number is not a perfect square.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 14: python algorithm to checks whether an integer is a perfect square”

Leave a Reply