当我的python范围对象停止值永远不会击中时会发生什么?
我正在学习Python,并且有一个小片段,如下所示:
for i in range(-10, 11, -6):
print(i)
这没有引发错误或输出。令人惊讶的是,我期望发生错误,因为11
的停止值永远不会被击中。有什么想法是吗?
I'm learning python and I have a little snippet that is shown below:
for i in range(-10, 11, -6):
print(i)
This did not throw up an error nor give an output. Surprisingly I expected an error, since that stop value of 11
would never be hit. Any ideas why that is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
范围代表一个不变的数字序列。
在这里。
在您的情况下:
因此,让我们尝试为您的情况生成范围的第一个元素
,但是-10少于停止,因此算法停止在这里产生空范围
,因此在您的代码范围内将等同于此:
此代码是完全有效的python,”范围和完成” - 这就是为什么(1)什么都没有打印为范围是空的,(2)您没有错误,因为代码是有效的
Range represents an immutable sequence of numbers.
Here is a documentation of
range
type.In your case:
so let's try to generate range first element for your case
but -10 is less than stop so algorithm stops here producing an empty range
so in your code range will be equivalent to this:
and this code is perfectly valid python, "iterate over an empty range and finish" - that is why (1) nothing printed as range is empty, and (2) you got no error as code is valid