Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met.
What I'm trying to do is this:
for index, item in enumerate(list2):
if item == '||' and list2[index-1] == '||':
del list2[index]
*<some action that resarts the whole process>*
That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:
['berry','||','pancake'] instead.
Thanks!
The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.
Note. You use the continue statement to restart a loop such as the while loop, for loop or for-in loop. If there are nested loops, the continue statement will restart the innermost loop.
You can use the input() function to restart a while loop in Python. And use the if statement to restart loop count.
I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration?
If it's the latter, then for
loops support continue
just like while
loops do:
for i in xrange(10):
if i == 5:
continue
print i
The above will print the numbers from 0 to 9, except for 5.
If you're talking about starting over from the beginning of the for
loop, there's no way to do that except "manually", for example by wrapping it in a while
loop:
should_restart = True
while should_restart:
should_restart = False
for i in xrange(10):
print i
if i == 5:
should_restart = True
break
The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With