问题描述
这是我的功能。
def is_square(n):
x = n ** 0.5
return((x >= 0) & (x % 1 == 0))
当我跑步时
is_square(-1)
我收到此错误消息:
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'
但是,此功能的各个组件都运行良好。
x = -1 ** 0.5
x >= 0
Out[185]: False
x % 1 == 0
Out[186]: True
(x >= 0) & (x % 1 == 0)
Out[189]: False
为什么我的功能不起作用?
解决方法
您在函数中所做的是将 x 定义为 sqrt(n)
。
对于 n = -1
表示 x = i (意思是 sqrt(-1)
)所以 >=
表达式没有实际意义。
当您单独测试函数的该部分时,代码被读取为 -(1**0.5)
。
您会看到,当您将其重写为 (-1)**(0.5)
时,它将不再起作用。