Python Forum

Full Version: Trouble interpreting prime number code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The assignment is to write a function that returns the number of prime numbers that exist up to and including a given number. The solution is below but I'm having trouble interpreting it. The part I don't understand is the 'for y in range(3,x,2)' loop. The first time it runs, x = 3 so I see it as 'range(3,3,2) but this doesn't make sense because the middle number represents up to but not including. So a range of 3-2 doesn't make sense. Also why is 'else:' not lined up with 'if'?

def count_primes(num):
primes = [2]
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in range(3,x,2): # test all odd factors up to x-1
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)

def count_primes2(num):
primes = [2]
x = 3
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_primes2(num):
    primes = [2]
    x = 3
    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)
range(3, x, 2) returns an iterable beginning with 3 and ending at x. The third argument is the "step" which instructs how to calculate the next value. So, range(3, 12, 2) would include 3, 5, 7, 9, 11.

The "else" is used with the for loop. That block executes once the for loop has completed per the documentation.