gpt4 book ai didi

python - 为什么会出现TypeError

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:33 24 4
gpt4 key购买 nike

为什么会这样:

def p3(x):
primes = [2]
for a in range(3, x, 2):
sqrt = a ** 0.5
for b in range(3, sqrt, 2):
if a % b == 0:
break
if a % b != 0:
primes.append(a)
return primes
print(p3(19))

返回这个:

TypeError: 'float' object cannot be interpreted as an integer, line 5

这是什么意思,我该如何更正它?
提前致谢,
刘易斯C

最佳答案

因为 sqrt 是一个 float ,而 range 需要严格的整数。

你可能想要这个:

for b in range(3, int(sqrt) + 1, 2):

关于python - 为什么会出现TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15173715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com