Mar-20-2020, 06:49 AM
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 part. In the first cycle of the loop, 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'? Can someone please help me understand how a range(3,3,2) works?
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 part. In the first cycle of the loop, 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'? Can someone please help me understand how a range(3,3,2) works?
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)