python中的神秘for循环 [英] Mysterious for loop in python

查看:26
本文介绍了python中的神秘for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果我然后在 exp 中执行 x,它会给我 False.但是如果我执行:

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

for x in exp:
    if x==3:
        print('True')

然后执行x in exp,返回True.这里发生了什么事?我没有给 x 分配任何东西.我有吗?我真的很困惑.

Then execute x in exp, it returns True. What's happening here? I didn't assign anything to x. Did I? I am really confused.

****对不起,如果我之前没有说过:x 之前没有定义.

****Sorry if I didn't say this before: x is not defined before.

谢谢大家.我现在明白了.随着 exp 的迭代,exp 的元素被分配给 x.并且 x in exp 等于最后一行代码中的 True 因为最后一个元素已分配给 x.

Thank you everyone. I understand it now. the elements of exp is assigned to x as exp is iterated over. And x in exp equals True in the last line of code because the last element has been assigned to x.

推荐答案

您似乎偶然发现 in 在 Python 中有些过载.

Seems like you stumbled about in being somewhat overloaded in Python.

  • 使用 x 在 exp,你在问Is x in exp?"
  • with for x in exp: ...,你告诉PythonFor每个元素inexp,称之为x然后做……"
  • with x in exp, you are asking "Is x in exp?"
  • with for x in exp: ..., you tell Python "For each element in exp, call it x and do ..."

后者会将 exp 中的每个值一个接一个地分配给 x,并使用该值执行循环体,所以在第一个迭代x被赋值为1,在第二个2,最后一个5.另外,x 在循环后保持这个值!

The latter will assign each of the values in exp to x, one after the other, and execute the body of the loop with that value, so in the first iteration x is assigned 1, in the second 2, and in the last 5. Also, x keeps this value after the loop!

因此,在循环之前,假设变量 x 已定义但具有其他值,x in exp 将返回 False,并且在循环之后,它返回True,因为x 仍然被赋值为exp 的最后一个值.

Thus, before the loop, assuming that the variable x is defined but has some other value, x in exp will return False, and after the loop, it returns True, because x is still assigned the last value from exp.

这篇关于python中的神秘for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆