for i in range(20,-1,0):
print(i)
而错误是:
Traceback (most recent call last):
File "D:/Python/b.py", line 1, in <module>
for i in range(20,-1,0):
ValueError: range() arg 3 must not be zero
for i in range(20,-1,0):
print(i)
Traceback (most recent call last):
File "D:/Python/b.py", line 1, in <module>
for i in range(20,-1,0):
ValueError: range() arg 3 must not be zero
range
函数接受三个参数:起始值 start、结束值 stop、步长 step。
range(20,-1,0):
要求从20
到-1
以步长0
进行转换。
这没有意义,因此Python会抛出错误。
在 for 循环中:
range(20,-1,0)
# ^^ can't be zero , Obviously Jump can't be zero
>>> range(20,-1, -1) #
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(20,-1, -2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0]
>>> range(0, 20, 1) # == range(0, 20) == range(20)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> range(0, 20, 2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
阅读Python文档:
因此,您遇到了range(stop)
range(start, stop[, step])
This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers
[start, start + step, start + 2 * step, ...]
. If step is positive, the last element is the largeststart + i * step
less than stop; if step is negative, the last element is the smalleststart + i * step
greater than stop.step
must not be zero (or else ValueError is raised).
ValueError: range() arg 3 must not be zero
的异常。
>>> range(20,-1,-1)
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
help(range):
range(...) range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j)
returns[i, i+1, i+2, ..., j-1];
start (!) defaults to0
. When step is given, it specifies the increment (or decrement). For example,range(4)
returns[0, 1, 2, 3]
. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
range() arg 3 must not be zero
,意思是range()函数的第三个参数不能为零。 - undefined0
,这是不可能的。我们如何通过0
从20
到达-1
呢? - undefined