Search code examples
pythonfunctionintegerbooleancomplex-numbers

My function for checking perfect squares does not work, but its components work individually


Here is my function.

def is_square(n):    
    x = n ** 0.5
    return((x >= 0) & (x % 1 == 0))

When I run

is_square(-1)

I get this error message:

Traceback (most recent call last):

  File "<ipython-input-183-33fbc4575bf6>", line 1, in <module>
    is_square(-1)

  File "<ipython-input-182-32cb3317a5d3>", line 3, in is_square
    return((x >= 0) & (x % 1 == 0))

TypeError: '>=' not supported between instances of 'complex' and 'int'

However, the individual components of this function work perfectly.

x = -1 ** 0.5

x >= 0
Out[185]: False

x % 1 == 0
Out[186]: True

(x >= 0) & (x % 1 == 0)
Out[189]: False

Why is my function not working?


Solution

  • What you are doing in your function is defining x as sqrt(n). For n = -1 that means x = i (meaning sqrt(-1)) so the >= expression has no real meaning. When you test that part of your function individually, the code is being read as -(1**0.5). You'll see that when you rewrite it as (-1)**(0.5) it won't work anymore.