python: restarting a loop

后端 未结 5 730
日久生厌
日久生厌 2020-11-30 08:50

i have:

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

But

5条回答
  •  情深已故
    2020-11-30 09:15

    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).

提交回复
热议问题