What is the execution process of while nested loops in python?

1.

while x < 3:
    print("x%d" % x)


    y = 0
    while y < 3:
        print("y%d" % y)
        print("")
        y += 1
        print("y%d" % y)


    print("")
    x += 1
    print("x%d" % x)

: ()

1
x = 0
y = 0

y = 1
y = 1

y = 2
y = 2

y = 3

x = 1


2

x = 1
y = 0

y = 1
y = 1

y = 2
y = 2

y = 3

x = 2


3

x = 2
y = 0

y = 1
y = 1

y = 2
y = 2

y = 3

x = 3


2.


x = 0
y = 0

while x < 3:
    print("x = %d" % x)


    while y < 3:
        print("y = %d" % y)
        print("")
        y += 1
        print("y = %d" % y)


    print("")
    x += 1
    print("x = %d" % x)

: ()

1

x = 0
y = 0

y = 1
y = 1

y = 2
y = 2

y = 3

x = 1



2

x = 1

x = 2



3

x = 2

x = 3

Why is this difference? After watching the video, the teacher only told me that the difference existed and analyzed the execution process himself, but it was based on the analysis of the results, and he always felt a little confused about the principle.

Is there any clearer way to understand

? Like python code from top to bottom, from left to right, LEGB principle?

Jul.03,2022
The essential difference of

lies in the position where the sentence y = 0 appears. If y = 0 appears outside the outer loop, then y will only be initialized to 0 before the start of the outer loop. If y = 0 occurs inside the outer loop and before the inner loop, then y will initialize to 0 before each inner loop.


because the process can be analyzed directly, the emphasis is on the sentence yellow0 :

  • example 2 y is on the outside of the outer while loop, so that within the first cycle of x , the inner loop of while y < 3 directly adds the value of y to 3 , resulting in no inner loop after the outer loop.
  • In
  • and example 1 , after the outer loop is executed for the first time, the y is executed in the second outer loop. At this time, the value of y is reset, so the inner loop will still be executed, and the third loop is the same.
Menu