当我的python范围对象停止值永远不会击中时会发生什么?

发布于 2025-02-07 05:51:28 字数 173 浏览 3 评论 0原文

我正在学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放手` 2025-02-14 05:51:28

范围代表一个不变的数字序列。

在这里。

在您的情况下:

  1. start = -10
  2. 停止= 11
  3. 步= -6

对于负步,该范围的内容仍由公式r [i] = start + step*i确定,但是约束是i> = 0和r [i]>停止。

如果r [0]不符合值约束。

,范围对象将为空。

因此,让我们尝试为您的情况生成范围的第一个元素

r[0] = -10 + -6 * 0
r[0] = -10

,但是-10少于停止,因此算法停止在这里产生空范围

>>> range(-10, 11, -6)
[]

,因此在您的代码范围内将等同于此:

for i in []:  # empty array, 0 iterations of loop, nothing printed to console
    print(i)

此代码是完全有效的python,”范围和完成” - 这就是为什么(1)什么都没有打印为范围是空的,(2)您没有错误,因为代码是有效的

Range represents an immutable sequence of numbers.

Here is a documentation of range type.

In your case:

  1. start = -10
  2. stop = 11
  3. step = -6

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.

A range object will be empty if r[0] does not meet the value constraint.

so let's try to generate range first element for your case

r[0] = -10 + -6 * 0
r[0] = -10

but -10 is less than stop so algorithm stops here producing an empty range

>>> range(-10, 11, -6)
[]

so in your code range will be equivalent to this:

for i in []:  # empty array, 0 iterations of loop, nothing printed to console
    print(i)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文