而循环和元组

时间:2015-02-09 04:30:14

标签: python python-3.x

我想定义一个函数,它返回两个给定数字之间所有整数的总和,但是我遇到了最后一行代码的问题,这些代码在下面。例如,用户输入两个整数,如(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))

2 个答案:

答案 0 :(得分:3)

您可以使用以下总和来执行此操作:

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

答案 1 :(得分:3)

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