Moving back an iteration in a for loop
Python loop using range
are by-design to be different from C/C++/Java for
-loops. For every iteration, the i is set the the next value of range(5)
, no matter what you do to i
in between.
You could use a while-loop instead:
i = 0
while i<5:
print i
if condition:
continue
i+=1
But honestly: I'd step back and think again about your original problem. Probably you'll find a better solution as such loops are always error-prone. There's a reason why Python for
-loops where designed to be different.
for
loops in Python always go forward. If you want to be able to move backwards, you must use a different mechanism, such as while
:
i = 0
while i < 5:
print(i)
if condition:
i=i-1
i += 1
Or even better:
i = 0
while i < 5:
print(i)
if condition:
do_something()
# don't increment here, so we stay on the same value for i
else:
# only increment in the case where we're not "moving backwards"
i += 1