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

标签 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.

我收到这个错误:

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,我不会出错,尽管它会增加一些不必要的计算。

最佳答案

您将 candidate 声明为整数。因此 candidate/2 也是一个整数,特别是 2。那么你的 range(2, candidate/2) 就是 range(2, 2)这没什么,所以 i 永远不会被初始化。您需要设置 candidate=5.0 使其成为 float ,一切都应该没问题。

编辑 正如评论中所指出的,简单地重新定义 candidate 会给你一个类型错误,但它应该足以让你走上正轨。请注意,range(x, y) 需要整数,您可能必须在使用 int() 进行除法或限制计算后再次转换为整数。此外,您可能想了解为什么提及与素数测试相关的 math.sqrt 函数

关于python2.7错误: UnboundLocalError: local variable 'i' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19961562/

相关文章:

python - scrapy 加速爬行

python - 如何修复 WebDriverException : The browser appears to have exited before we could connect?

python - 更优雅地改变数组的数组

opencv - cv2 问题中的 Fourcc

python - 抓取一行的一部分直到出现空白

Python 2.7 - 如何检查是否按下了 SHIFT-Key 或 CTRL+Key?

python - 这个打印语法是什么? (打印右移)

python - numpy数组比较的高效Python实现

python 仅运行 apschedule BlockingScheduler 一次

python - 如何在 python 中为多种语言编写文档字符串