Search code examples
pythonloopsnested

Does the inner loop run first?


I am trying to understand the order of nested loops. The first loop through the outer loop returns

13 16 19 113 116 119

It looks like it starts with the outer loop first then fully goes through the inner loop iterations and back to outer loop until iterations, is that correct?

Is this the case for most nested loops?

i1 = 1
while i1 < 19:
    i2 = 3
    while i2 <= 9:
        print(f'{i1}{i2}', end=' ')
        i2 = i2 + 3
    i1 = i1 + 10

When I went through the 2nd iteration of the outer loop i2 overwrites back to 3 (instead of 6) which is what is confusing me and is incorrect.


Solution

  • Yes, you are correct about the order of execution in nested loops. The outer loop will iterate first, and for each iteration of the outer loop, the inner loop will complete all its iterations before moving to the next iteration of the outer loop.