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:
- we first imports the math module: to use its sqrt function.
- It then takes an integer input: from the user using the input function and converts it to an integer using the int function.
- Next, the program calculates the square root: of the input number using the sqrt function from the math module.
- 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.
- Otherwise, it prints: a message saying that the input number is not a perfect square.
Younes Derfoufi
my-courses.net
[…] Exercise 14 || Solution […]