2015-02-09 79 views
0

我想定義一個函數,它返回兩個給定數字之間的所有整數的總和,但我在下面的最後一行代碼中遇到了問題。例如,用戶輸入兩個整數,例如(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

我試着修復你的代碼格式,但是'x = int'等沒有意義 – 2015-02-09 04:34:34

回答

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

有趣! – 2015-02-09 04:48:27