There are two loops in the code, one inside the other. This will help you understand the code if you replace the inner loop with a function. Then make sure that the function is correct and can stand by itself (separately from the external circuit).
Here is my rewriting source code. This rewriting works great.
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() does not apply to the loop index of the outer loop. This is a standalone net function. The problem of adding p inside the inner loop was a problem, and this decomposed version has no problem.
Now we can easily rewrite it with for loops, and I think the code will be 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 into. So the inner loop that checks for < n can just be called range(2, n) , but for the outer loop where we want <= n , we need to add it to n to include n : range(2, n+1)
Python has built-in stuff that is fun. You do not need to learn all these tricks right away, but here you can write is_prime() :
def is_prime(n): return not any(n%i == 0 for i in range(2, n))
This works the same as the for is_prime() loop version. It sets i values โโfrom range(2, n) and checks each, and if the test ever fails, it stops checking and returns. If he checks n for every number in the range, and none of them evenly divide n , then the number is prime.
Again, you donโt need to learn all these tricks right away, but I think they are very funny when you learn them.