Python find Nth prime

Viewed 253

I am trying to find the nth prime number, without looking at other solutions I am building this function

def Nth_Prime(Target):

    Primes = [2,3,5,7,11,13,17,19]
    Num = 20
    N=8
    Count=0

    while(N<Target):
        for i in Primes:
            if Num%i==0:
                Num+=1
                i=2
            else Num%i!=0:
                Count+=1
                if Count==len(Primes):
                    i=2
                    Primes.append(Num)
                    N+=1
                    print(Primes)
                    Num+=1
                    print(Count)

Nth_Prime(10002)

Now, while it may not be the most efficient, what I am trying to understand is why I can't reset my variable I to the beginning of the array for each loop? the function correctly finds 23 as the next prime number then it goes wrong

help appreciated.

EDIT: I got it! Thanks to all, time to clean it up a little and make it more aesthetic

def Nth_Prime(Target):

    Primes = [2,3,5,7,11,13,17,19]
    Num = 20
    N=8
    Count=0
    x=0

    while(N<Target):
        i = Primes[x]
        if Num%i==0:
            Num+=1
            x = 0
        elif Num%i!=0:
            Count+=1
            x+=1
            if Count==len(Primes):
                Primes.append(Num)
                N+=1
                Num+=1
                Count = 0
                x=0
    print(Primes[10000])

Nth_Prime(10002)
1 Answers

No matter what you do with i variable in the loop for is going to reinitialize it with the next value from primes list. That's just how the for loop works.

so you can imagine the first line of for loop to be

for loop:
    i = Primes[x] # initialize
    ... # do stuff
    x+=1
    i = 'something' # HAS NO EFFECT for next iteration
Related