Same variable name for different values in nested loops.

前端 未结 6 1092
囚心锁ツ
囚心锁ツ 2020-12-22 12:26

This code is perfectly valid Python

x=[[1,2,3,4], [11,22,33,44]]
for e in x:
    for e in e:
        print e

Can someone please tell me why

6条回答
  •  眼角桃花
    2020-12-22 12:54

    'e' in this case are in the same scope. If you do something like...

    for i in range(MAX):
        if(some_condition == True):
            for i in range(5):
                #do stuff
    

    If the code traverses into the inner for loop, it'll increment the "outer i" 5 times, causing you to skip out on those runs.

    With the code you posted, it doesn't produce a syntax error, and it happens to work out from a logical perspective, but there may be other examples where you will get the wrong result.

提交回复
热议问题