Your code has two loops, one inside another. It should help you figure out the code if you replace the inner loop with a function. Then make sure the function is correct and can stand on its own (separate from the outer loop).
Here is my rewrite of your original code. This rewrite works perfectly.
def is_prime(n):
i = 2
while i < n:
if n%i == 0:
return False
i += 1
return True
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
if is_prime(p):
print p,
p=p+1
print "Done"
Note that is_prime()
doesn't touch the loop index of the outer loop. It is a stand-alone pure function. Incrementing p
inside the inner loop was the problem, and this decomposed version doesn't have the problem.
Now we can easily rewrite using for
loops and I think the code gets improved:
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
n = int(raw_input("What number should I go up to? "))
for p in range(2, n+1):
if is_prime(p):
print p,
print "Done"
Note that in Python, range()
never includes the upper bound that you pass in. So the inner loop, which checks for < n
, we can simply call range(2, n)
but for the outer loop, where we want <= n
, we need to add one to n
so that n
will be included: range(2, n+1)
Python has some built-in stuff that is fun. You don't need to learn all these tricks right away, but here is another way you can write is_prime()
:
def is_prime(n):
return not any(n%i == 0 for i in range(2, n))
This works just like the for
loop version of is_prime()
. It sets i
to values from range(2, n)
and checks each one, and if a test ever fails it stops checking and returns. If it checks n
against every number in the range and not any of them divide n
evenly, then the number is prime.
Again, you don't need to learn all these tricks right away, but I think they are kind of fun when you do learn them.