Mysterious for loop in python

后端 未结 5 1322
广开言路
广开言路 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条回答
  •  旧时难觅i
    2020-12-11 08:49

    The syntax is similar, but they mean two different things.

    x in exp is a conditional expression; it searches to see if the value of x appears in the list exp. If it's there, the expression evaluates to True, otherwise, False. You can also use not in.

    for x in exp introduces a loop where x iterates over the elements of exp. The loop body will be called once for each element, and within the body, x will be set to each element successively.

提交回复
热议问题