what happened when using the same variable in two layer loops in python?

前端 未结 6 1741
星月不相逢
星月不相逢 2021-01-12 14:18

I test the following code:

for i in range(3):
    for i in range(3,5):
        print \"inner i: %d\"%(i)
    print \"outer i: %d\"%(i)

and

6条回答
  •  猫巷女王i
    2021-01-12 14:40

    There's only one i, not two. When the inner loop is entered, it changes i, and keeps changing it until the inner loop exits. The next iteration of the outer loop then sets i to the next value in its range, but you never see it because you immediately enter the inner loop once more, again changing i.

    This is of course very bad practice. You should never modify the variable in a for loop while that loop is active.

提交回复
热议问题