0

I have two functions which are identical the function finds all the prime number up to a given number

def count_primes2(num):
    primes = [2,3,]
    x = 5
    if num < 2:
        return 0
    while x <= num:
        for y in primes:  # use the primes list!
            if x%y == 0:
                x += 2
                break
        else:
            primes.append(x)
            x += 2
    print(primes)
    return len(primes) 


def count_primes3(num):
    primes = [2]
    x = 3  
    if num < 2 :
        return 0
    while x <= num:
        for y in range(3,x,2):
            if x%y == 0:
                x += 2               
                break                
        else:
            primes.append(y)
            x += 2    
    print(primes)   

count_primes2 works perfectly and gives me an out put however count_primes3 gives me an UnboundLocalError at primes.append(y)

The function completes if I comment that step out. Can any one tell me why this happens?

user2653663
  • 2,573
  • 1
  • 14
  • 20

1 Answers1

2

You're trying to append y instead of x like you do in count_primes2.

def count_primes3(num):
    primes = [2]
    x = 3  
    if num < 2 :
        return 0
    while x <= num:
        for y in range(3,x,2):
            if x%y == 0:
                x += 2               
                break                
        else:
            primes.append(x) ### This shouldn't be a y
            x += 2    
    print(primes)   
user2653663
  • 2,573
  • 1
  • 14
  • 20