gpt4 book ai didi

python2.7错误: UnboundLocalError: local variable 'i' referenced before assignment

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:16 24 4
gpt4 key购买 nike

<分区>

运行此 python 脚本时出现错误。

def thousandthPrime():
count=0
candidate=5 #candidates for prime no. these are all odd no.s Since starts at 5 therefore we find 998th prime no. as 2 and 3 are already prime no.s
while(True):
#print 'Checking =',candidate
for i in range(2,candidate/2): #if any number from 2 to candidate/2 can divide candidate with remainder = 0 then candidate is not a prime no.
if(candidate%i==0):
break
if i==(candidate/2)-1: # If none divide it perfectly, i will reach candidate/2-1 eventually. So, this is a prime number.
count+=1
print 'No. of prime no.s found excluding 2 and 3 =',count, '--->',candidate
if(count==998):
print 'The thousandth prime is',candidate
break
candidate+=2 # to go to the next odd number.

我收到这个错误:

File "/home/.../xxx.py", line 19, in thousandthPrime
if i==(candidate/2)-1: # If none divide it perfectly, i will reach candidate/2-1 eventually. So, this is a prime number.
UnboundLocalError: local variable 'i' referenced before assignment

但是,如果我将 candidate/2 替换为 candidate,我不会出错,尽管它会增加一些不必要的计算。

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