简体   繁体   中英

Why does this Python nested for loop produce the output I get?

I'm very new to learning python, though I understand the basics of the looping, I am unable to understand the method in which output is arrived at.

In particular, how does the mapping of all three for loops happen to give the desired output, as I finding it impossible to understand the logic to be applied, when I try to write the output on paper without referring to IDE.

Code:

n = 4
a = 3
z = 2
for i in range(n):
    for j in range(a):
        for p in range(z):
            print(i, j, p)

Output is:

0 0 0
0 0 1
0 1 0
0 1 1
0 2 0
0 2 1
1 0 0
1 0 1
1 1 0
1 1 1
1 2 0
1 2 1
2 0 0
2 0 1
2 1 0
2 1 1
2 2 0
2 2 1
3 0 0
3 0 1
3 1 0
3 1 1
3 2 0
3 2 1

The first loop iterates four times.

The second loop iterates three times. However since it is embedded inside the first loop, it actually iterates twelve times (4 * 3.)

The third loop iterates two times. However since it is embedded inside the first and second loops, it actually iterates twenty-four times (4 * 3 * 2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM