为什么在 for 循环中使用负范围时 Python 不抛出 ValueError?

Why doesn't Python throw a ValueError when you use a negative range in a for loop?

我想知道为什么这不会引发 ValueError:

>>>    for i in range(-1):
...        print "something"
...
>>>

这种否定论据有没有用处?

范围也可以接受负步

In [2]: list(range(0, -10, -1))
Out[2]: [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

更不用说负数的正步进范围了。

In [3]: list(range(-9, 1))
Out[3]: [-9, -8, -7, -6, -5, -4, -3, -2, -1, 0]

至于为什么它不会在一个否定的参数版本上抛出错误,我认为这只是 Zen 的一个例子

Special cases aren't special enough to break the rules.

默认情况下,range函数从0开始。此外,步长默认为正1。您只为函数提供了一个参数(停止点),该参数是 -1。因此,它试图将 递增 从 0 到 -1。

请参阅 range()

上的文档

If the start argument is omitted, it defaults to 0.

如果您想要负数,您需要包括 startstopstep 值:

range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

没有抛出异常,因为它的行为与文档描述的一样。