Python For loop和range函数

2024-10-01 17:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

def countMe(num):
    for i in range(0, num, 3):
        print (i)

countMe(18)

def oddsOut(num1, num2):

    for i in range(num1):
        for j in range(num2):
            print(i*j)

oddsOut(3, 8)

我不明白范围函数是如何工作的:

  • countMe中,代码不应该一直到18
  • 为什么最后一个数字打印在countMe15,而不是18
  • 为什么在第二个函数oddsOut中,即使j是8,函数也只到7,而不是8
  • 为什么最后一个数字印在oddsOut14中。在

Tags: 函数代码infordefrange数字num
3条回答

Python中的范围不包括结束值。这与切片一致。在

如果您需要一种方法来记住这一点,请考虑range(10)有10个元素——数字0到9。在

例如,范围中的stop参数不包括该数字

for i in range(0,5):
    print i

会打印0-4但不是5。在

好吧,从帮助中:

>>> 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
>>> 

相关问题 更多 >

    热门问题