user3498327
user3498327

Reputation: 21

Reiterate a for loop?

I want my for loop to iterate over from the beginning each time instead of starting where it left off.

primes = [2]
cur = 3
count = 1
while count < 10:
    for num in primes:
        if cur % num == 0:
            cur += 2
    primes.append(cur)
    print cur
    cur += 2
    count += 1
print primes

I couldn't figure out what was wrong for a while and I kept on getting 27 as prime. Putting my code into PythonTutor showed my that it was marked as prime because it began to iterate for 27 after the check to see if it was divisible by 3. Is there any way to reiterate from the beginning or should I try to find primes doing something else? Thanks

Upvotes: 0

Views: 3382

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121966

You can fix this by adding a while loop and using break and else to control the flow appropriately:

primes = [2]
cur = 3
count = 1
while count < 10:
    while True:
        for num in primes:
            if cur % num == 0:
                cur += 2
                break # restart 'for' loop
        else: # reached end of 'for' loop without restarting
            break # leave 'while' loop
    primes.append(cur)
    cur += 2
    count += 1

However, that is pretty awkward! You can simplify to:

primes = [2]
cur = 3
while len(primes) < 10:
    if all(cur % num for num in primes):
        primes.append(cur)
    cur += 2

Note that all is "lazy", so it will return False as soon as cur % num == 0.

Upvotes: 4

Related Questions