Mysterious for loop in python

后端 未结 5 1325
广开言路
广开言路 2020-12-11 08:14

Let exp = [1,2,3,4,5]

If I then execute x in exp, it will give me False. But if I execute :

for x in exp:
             


        
5条回答
  •  醉话见心
    2020-12-11 08:55

    for x in ... inherently assigns values to x, because x is the loop variable in a for loop.

    Each iteration of the loop assigns a value into x; Python doesn't create a new variable scope for loops.

    for x in (1, 2, 3):
        foo(x)
    

    is the equivalent of...

    x = 1
    foo(x)
    x = 2
    foo(x)
    x = 3
    foo(x)
    

提交回复
热议问题