python2.7错误:UnboundLocalError:在赋值之前引用的局部变量'i'

ast*_*123 3 python python-2.7

运行这个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.
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

但是,如果我替换候选人/ 2与候选人,我没有错误,虽然它增加了一些不必要的计算.

CDs*_*ace 6

你声明candidate是一个整数.因此candidate/2也是一个整数,特别是2.然后你的range(2, candidate/2)range(2, 2)什么都没有,所以i永远不会被初始化.你需要设置candidate=5.0它使它成为一个浮点数,一切都应该很好.

编辑 正如评论中指出的那样,简单地重新定义candidate会给你一个类型错误,但它应该足以让你走上正轨.注意,range(x, y)期望整数,您可能必须在除法或限制计算后再次转换为整数int().此外,您可能想要查看为什么math.sqrt提到的功能与素性测试有关