【发布时间】:2023-03-03 07:52:23
【问题描述】:
这里是初学者,尝试使用 Python3 理解 for 循环。有人可以在下面的代码中解释为什么在 for 循环之外返回值 5 吗?如果在 for 循环之外调用变量,Python 是否只返回最大数?
for x in range(0,6):
print(x) #here is the expected output of (0,1,2,3,4,5)
print(x) #this just returns 5, why?
【问题讨论】:
-
Python 保留循环中使用的变量的最后一个值。尝试使用范围内的值。
-
好问题!我认为这会给你一个错误,因为
x应该是循环的局部变量,但显然它不会立即被垃圾收集。 -
@nbro for 循环不会创建新范围。这与垃圾回收无关,变量是为整个命名空间(函数和模块)定义的。另请参阅this answer。
标签: loops python-3.x for-loop