While 循环和元组

While loop and tuples

我想定义一个函数,该函数 returns 两个给定数字之间的所有整数之和,包括两个给定数字,但我在使用下面的最后一行代码时遇到了问题。例如,用户输入两个整数,例如 (2,6),函数会将所有值相加,即 2+3+4+5+6=20。我不知道如何使我的函数从输入 (x) 开始并在输入 (y) 结束。另外,我想使用 while 循环。

def gauss(x, y):
    """returns the sum of all the integers between, and including, the two given numbers

    int, int -> int"""
    x = int
    y = int
    counter = 1
    while counter <= x:
        return (x + counter: len(y))

您可以按如下方式使用总和来完成此操作:

In [2]: def sigma(start, end):
   ...:     return sum(xrange(start, end + 1))
   ...: 

In [3]: sigma(2, 6)
Out[3]: 20

如果你想使用 while 循环,你可以这样做:

In [4]: def sigma(start, end):
   ...:     total = 0
   ...:     while start <= end:
   ...:         total += start
   ...:         start += 1
   ...:     return total
   ...: 

In [5]: sigma(2, 6)
Out[5]: 20
def gauss(x, y):
    """returns the sum of all the integers between, and including, the two given numbers
    int, int -> int"""

    acc = 0 # accumulator
    while x <= y:
        acc += x
        x += 1

    return acc

旁白:更好的方法是完全不使用 sumrange 或循环

def gauss(x, y):
    return (y * (y + 1) - x * (x - 1)) // 2