运行此 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
但是,如果我只用候选者替换候选者/2,我不会得到任何错误,尽管它增加了一些不必要的计算。