0
def loop():
    for i in range (0,9):
        pass
        if i == 3:
            i = i +3

        print(i)

loop()

Current output :

0
1
2
6
4
5
6
7
8

Expecting output:

0
1
2
6
7
8
9

Does this have to do something with the way stack frames are created in Python? Why doesn't the number of iterations reduce even though we increment i ?

cs95
  • 379,657
  • 97
  • 704
  • 746
elixir
  • 173
  • 2
  • 13
  • 2
    `i` isn't a magical variable that controls the loop. You might want to use `while` instead. – cs95 Feb 17 '18 at 03:56

1 Answers1

7

The value of i does not have any bearing over the loop execution. That is determined by... range(0, 9) (or, range(9)). The for loop is meant to iterate over an iterator, and iterates for a set number of iterations. If you want to skip loop iterations, you'd do that with a condition controlled continue.

For your case, though, I'd suggest the while loop, the more idiomatic choice for this sort of requirement.

i = 0
while i < 9:
    ... # something happens here
    if i == 3:
        i += 3
    else:
        i += 1

Further reading; When to use "while" or "for" in Python

cs95
  • 379,657
  • 97
  • 704
  • 746