为什么 for 循环不重置 range() 函数?


我有一个代码:
x = 6
for y in range(x):
print(y)
x -= 2

给出:0, 1, 2, 3, 4, 5

我错误地预测它会给出以下两种结果之一:

  1. 0, 0, 0因为x从6到4到2再到0,所以只会打印3个y。此外,据我所知,在每个循环之后,它会回到for循环语句,从而完全重置range(),现在每个y都是0。我跑在PythonTutor和指针的代码也似乎回到循环语句每次循环后。

  2. 0, 1, 2因为x从6到4到2再到0,所以只会打印3个y。我认为这可能是可能的,虽然y采用原始范围的值(即6),但它将受到每个新x的限制,因此只打印3个y

可能性1对我来说是最直观的(尽管是错误的),我不确定如何去理解为什么答案是这样的。

range(x)产生的range实例在调用range时使用x的值。它不会在每次需要从范围中获取新值时重复检查x的值。你的代码是一样有效的

x = 6
for y in [0, 1, 2, 3, 4, 5]:
print(y)
x -= 2

x的任何操作都不会对正在迭代的range对象产生任何影响。

range()调用在循环开始时从x创建一个range对象。改变x后没有影响被用于迭代range对象。

如果你想改变你在一个循环中进行多少次迭代,你可能想看看使用while

试试这个:

# Firstly you assign 6 to the variable x
x = 6 
# 'y' will now be assigned to the numbers [0, 1, 2, 3, 4, 5, 6] because the range is 'x' which is 6.
# by printing 'x' it will execute [0, 1, 2, 3, 4, 5, 6] but since x is 'x -2' which is the same as  '6 - 2'  it will print out the number 6 and -2 until it gets to the range which is -6. the output will be 6 numbers [6, 4, 2, 0, -2, -4] 

for y in range(x):
print(x)
x = x - 2
# i am showing you a way of making it give you your expected output [6, 4, 2, 0, -2, -4] 

最新更新