Python,以下代码有什么问题?range(20,-1,0)返回错误。

3
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

2
你想要做什么? - undefined
7
错误提示:range() arg 3 must not be zero,意思是range()函数的第三个参数不能为零。 - undefined
1
您正在指定一个步长为0,这是不可能的。我们如何通过020到达-1呢? - undefined
4
这个问题似乎不适合这里,因为它涉及从回溯中读取错误信息。 - undefined
翻转第二个和第三个参数:list(range(20,0,-1)) - undefined
3个回答

7

range 函数接受三个参数:起始值 start、结束值 stop、步长 step。

range(20,-1,0):

要求从20-1以步长0进行转换。

这没有意义,因此Python会抛出错误。


3

在 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 largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised).

因此,您遇到了ValueError: range() arg 3 must not be zero的异常。

1
我想你正在寻找:

>>> 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 to 0. 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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接