perfect square checker says 144 is not a perfect square

Question:

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")
Asked By: siddhantuniyal

||

Answers:

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)
    return root ** 2 == number

print(is_perfect_square(144))
Answered By: Jobo Fernandez

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.

Answered By: D.L
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.