好吧,从帮助中:>>> 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.
所以最后一个增量不是stop,而是stop之前的最后一步。在in countMe shouldn't the code go up till 18 ;
why is the last number printed in countMe 15, and not 18 ;
why is that in the second function oddsOut the function only founts till 7 for j and not 8 even though j is 8 ;
why is the last number printed in oddsOut 14.
更一般地说,这些问题的答案是,在大多数语言中,一个范围被定义为[start:stop[,也就是说,范围的最后一个值从不包含,索引总是从0开始。混乱的是,在一些语言中,当处理算法时,范围从1开始,并包含最后一个值。在
如果您希望在最后一个值中包含:
^{pr2}$
或者在你的例子中:>>> def countMe(num):
>>> for i in range(0, num+1, 3):
>>> print (i)
>>>
>>> countMe(18)
0
3
6
9
12
15
18
>>>