[英]Variables inside and outside of a for loop
The question itself lies inside the code (or questions themselves lie , since there are several question marks).问题本身位于代码中(或者问题本身位于代码中,因为有几个问号)。
Code:代码:
i = -3 # Where am I? Am I not the 'i' that should be inside the for loop?
print("before the cycle:", i)
for i in range(5): # Why am I starting from 0, not from -3?
print("cycle variable:", i)
i += 1 # How come I change nothing in terms of amount of loop iterations?
print("(?) variable:", i) # And why do I start from the same 0?
Output: Output:
before the cycle: -3
cycle variable: 0
(?) variable: 1
cycle variable: 1
(?) variable: 2
cycle variable: 2
(?) variable: 3
cycle variable: 3
(?) variable: 4
cycle variable: 4
(?) variable: 5
Where should I look up the information about such variable behavior?我应该在哪里查找有关此类可变行为的信息?
My guess is that the question about loop start is somehow related to LEGB rule, and i
is both declared and defined (?!) right after for
keyword.我的猜测是关于循环开始的问题在某种程度上与 LEGB 规则有关,并且
i
在for
关键字之后被声明和定义(?!)。
But again, I seek knowledge, not guesses.但是,我再次寻求知识,而不是猜测。
You are mistaken for the functionality of range
.您误认为
range
的功能。 It is a sequence generator which starts with 0
by default and hence it produces 0, 1, 2, 3, 4 for range(5)
.它是一个序列生成器,默认情况下以
0
开头,因此它为range(5)
生成 0、1、2、3、4。
If you want to step from -3 in 5 steps you could do:如果你想分 5 步从 -3 开始,你可以这样做:
i = -3
range(i, i+5)
Your questions boil down to the mechanics of generators :您的问题归结为发电机的机制:
for i in range(5): # Why am I starting from 0, not from -3?
In this line, the range(5) is a generator that will produce values: 0, 1, 2, 3, 4, sequentially.在这一行中, range(5)是一个生成器,它将依次生成值:0、1、2、3、4。 Even if you changed the value of i before the for loop, or you will change the value of i inside the for loop, the for loop will take the next value from the generator and will execute until the generator raises StopIteration , which basically means that it ran out of values to generate.
即使您在 for 循环之前更改了i的值,或者您将在 for 循环内更改i的值,for 循环将从生成器获取下一个值并执行直到生成器引发StopIteration ,这基本上意味着它用完了要生成的值。
I think you've understood more or less correctly.我想你已经或多或少地理解了。 "for i" assigns the items yielded by the range generator to i.
“for i”将范围生成器生成的项目分配给 i。 "range(5)" defaults to a range from 0 to 5. You could add a second parameter, for instance
“range(5)”默认为 0 到 5 的范围。例如,您可以添加第二个参数
range(-3, 5)范围(-3, 5)
Or if you want to iterate from a number stored in an earlier variable, you could give it a different name, and pass it as the first argument:或者,如果您想从存储在较早变量中的数字进行迭代,您可以给它一个不同的名称,并将其作为第一个参数传递:
x = 2 x = 2
for i in range(x, 5):对于范围内的我(x,5):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.