tags:

views:

1149

answers:

3

i have:

for i in range(2,n):
    if(something):
       do something
    else:
       do something else
       i = 2 **restart the loop

But that doesn't seem to work. Is there a way to restart that loop?

Thanks

+7  A: 

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

Greg Hewgill
+10  A: 

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop
gnomed
thanks Perrow, not much of a python person... yet.
gnomed
Just a reminder: with a while loop, make sure you have a termination condition that can always be satisfied.
Brandon Corfman
I reckon this will terminate when i>=n
gnomed
But there's nothing preventing i from continuing to reset to 2 indefinitely, depending on the "if something" test.
Brandon Corfman
So it depends more on the if-test than the loop invariant? Is there another solution that avoids this while staying simple(because simplicity is key)? Won't there always be the same risk in any loop with the potential to restart?
gnomed
+3  A: 

The for statement is not as simple. Understanding Python's "for" statement.

Igal Serban