简体   繁体   中英

2 dimensional loop doesn't work as expected in python

I have this loop:

i = 0
j = 1
size = 4

for i in range(i, i + size):
    for j in range(j, j + size):
        print(i, j)

I expected it to have the following output:

0 1
0 2
0 3
0 4
1 1
1 2
. .
. .
. .
3 4

But I get this instead:

0 1 
0 2 
0 3 
0 4 
1 4 
1 5 
1 6 
1 7 
2 7 
2 8 
2 9 
2 10
3 10
3 11
3 12
3 13

It's like the value of j is being updated after each outer loop iteration. Why is this happening?

You are setting variable initially and using variables with the same name in the loop... use variable with different names in the loop like a and b :

i = 0
j = 1
size = 4

for a in range(i, i + size):
    for b in range(j, j + size):
        print(a, b)

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

It's like the value of j is being updated after each outer loop iteration. Why is this happening?

This is because you set the value of j with for j in range(j, j + size) . In other words, j is set to a new value each time the inner loop iterates. Similarly, you set i to a new value each time the outer loop iterates just like you see in the output.

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