[英]What's the logic behind stop value of range function with negative step value in python
My question is very simple.我的问题很简单。 I'm new to python and I recently learnt about range()
in python.我是 python 的新手,我最近了解了 python 中的range()
。 And I go through an sample program in that problem they asked to print reverse multiplication table of 3 using range function And my code is我通过一个示例程序 go,他们要求使用范围 function 打印 3 的反向乘法表,我的代码是
for i in range(30,3,-3):
print(i)
But the output is not same as I expected.但是 output 和我预期的不一样。 The output does not included 3. I don't know why. output不包括3。我不知道为什么。 My question the last value should be (stop value -1) ie, 2 in this case.我的问题最后一个值应该是(停止值-1),即在这种情况下为 2。 So 3 should also to be printed but not so.所以 3 也应该被打印,但不是这样。 Please explain why.请解释原因。 Does I misunderstood the logic?我误解了逻辑吗? If so please explain.如果是这样,请解释。
The python docs for range(start, stop[, step]) says the following: : range(start, stop[, step])的 python 文档说明如下:
For a negative step, the contents of the range are still determined by the formula r[i] = >start + step*i, but the constraints are i >= 0 and r[i] > stop.对于负步长,范围的内容仍然由公式 r[i] = >start + step*i 确定,但约束是 i >= 0 和 r[i] > stop。
This means the stop argument isn't included in the range calculation.这意味着停止参数不包括在范围计算中。
range()
excludes the stop point when generating your list (well actually they return a generator). range()
在生成列表时排除了停止点(实际上它们返回了一个生成器)。 You should change 3
to 2
, then it will include 3您应该将3
更改为2
,然后它将包括 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.