Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python2.7 error: UnboundLocalError: local variable 'i' referenced before assignment [duplicate]

I get an error when I run this python script.

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.

I get this error:

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

But if I replace, candidate/2 with just candidate, I get no errors, although it increases some unnecessary calculations.

like image 442
aste123 Avatar asked Nov 20 '25 05:11

aste123


1 Answers

You're declaring candidate as an integer. Thus candidate/2 is also an integer, specifically 2. Then your range(2, candidate/2) is range(2, 2) which is nothing, so i is never initialized. You'll need to set candidate=5.0 to make it a float and all should be well.

EDIT As pointed out in the comments, simply re-defining candidate will give you a type error, but it should be enough to get you on track. Note, range(x, y) expects integers, you you may have to convert to an integer again after the division or limiting calculation using int(). Also, you may want to look into why the math.sqrt function was mentioned related to primality testing

like image 157
CDspace Avatar answered Nov 21 '25 17:11

CDspace