amir darvish
amir darvish

Reputation: 17

Why did the index of the for loop change inappropriately?

Could anyone tell me why the index of loop is 1 whereas it is initialized as 2 in the for loop?

for i in range(0, len(input)):
    if input[i] == 'A':
        if input[i + 1] == 'B':
            flag1 = True
            if i + 2 < len(input):
                i = i + 2

After the first loop, i changes to 1, but in the loop it is 2.

Upvotes: 0

Views: 34

Answers (1)

ForceBru
ForceBru

Reputation: 44838

The value of i is controlled by range(0, len(input)). You can modify i inside the loop, but on the next iteration it will be reset to the next value in the range.

To have complete control over i, use a while loop:

i = 0
while i < len(input):
   # body
   i += 1

Upvotes: 2

Related Questions