Moving back an iteration in a for loop

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)