I want to solve a problem given by our teacher. The problem is: make a Python program that verifies if a number is a perfect square. If it's a perfect square it, shows a message and if not it shows another message.
This is my attempt:
n = int(input('choose a number'))
for i in range(1,n):
if n//i==i:
d=i
print(n,'is a perfect square and its root is,',d)
During my attempt, I couldn't add the else
condition where the number is not a perfect square.
CodePudding user response:
you gave this a good go. Has your teacher taught you about importing modules yet? Basically, a module is like a Python file, and you can take functions from that file and use them in your file. One module is 'math' and holds a function called 'sqrt' that calculates the square root of a given number. If this square root is a whole number (has no remainder) the given number is square -- is not, it's not square. See the program I wrote below:
import math
num = int(input("Number = "))
square_root = math.sqrt(num)
if square_root % 1 == 0:
print(f"It's square. {int(square_root)} squared gives {num}")
else:
print("It's not square")