I started learning python yesterday , and I realized I can make a perfect square checker using functions and the isinstance function. However , my code says 144 is not a perfect square. What am I doing wrong?
My Code :
def sqrt():
x = int(input("Enter a number:"))
a = x ** 0.5
return a
b = sqrt()
if isinstance ( b , int) == True:
print("It is a perfect square")
if isinstance( b , int) == False:
print("It is not a perfect square")
CodePudding user response:
Keep in mind that number ** 0.5
will always result to a floating value. Example: 144 ** 0.5 == 12.0. Because of this, isinstance(b , int)
will always be False.
This is an alternative solution among many other possible solutions:
def is_perfect_square(number):
root = int(number ** 0.5)
if root ** 2 == number:
return True
return False
print(is_perfect_square(144))
CodePudding user response:
Use the modulo operator %
to check for a remainder of zero.
def is_perfect_square(number):
sqrt = number**0.5
return True if sqrt % 1 == 0 else False
>>> is_perfect_square(25)
True
>>> is_perfect_square(100)
True
>>> is_perfect_square(17)
False
CodePudding user response:
The type of b
in the original code is a float
.
you can see this by adding type(b)
to the end of the code which would return <class 'float'>
.
so you could change the code to this:
def sqrt():
x = int(input("Enter a number:"))
a = x ** 0.5
return a
b = sqrt()
if b - int(b) == 0:
print("It is a perfect square")
else:
print("It is not a perfect square")
This method avoids checking for type, but instead checks if the decimal part == 0
which is sufficient for a square.
Note: there are other methods.