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

前端 未结 6 1666
星月不相逢
星月不相逢 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条回答
  •  借酒劲吻你
    2021-01-12 14:37

    In the inner loop you are assigning a different variable to i. Since it is the same variableit always prints 4 (the last value i was assigned in the inner loop. However, when you go to the next iteration of outer loop it will be set to the next value (i.e. 2 for the second outer loop). You should print outer loop before the inner loop to see the effect more clearly:

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

提交回复
热议问题