2016-04-30 28 views
0

對不起,我不得不問這樣一個簡單的問題,但我一直試圖做一段時間沒有運氣,儘管四處搜索。 我想定義一個函數,它將得到X的用戶輸入,然後添加從0到X的每個整數,並顯示輸出。Python ==函數計算低於定義變量的所有整數,包含

例如,如果用戶輸入5,結果應該是的總和1 + 2 + 3 + 4 + 5

我不能找出如何提示輸入變量的用戶,並然後將該變量傳遞給函數的參數。謝謝你的幫助。

def InclusiveRange(end): 
     end = int(input("Enter Variable: ") 
     while start <= end: 
       start += 1 
     print("The total of the numbers, from 0 to %d, is: %d" % (end, start)) 
+0

只是一個關於編碼風格注:Python中的約定是使用類名首字母大寫和函數名稱的lower_case_with_underscores。所以你的函數最好稱爲「inclusive_range」,或者甚至更好的名稱,它實際上描述了函數的功能(例如「sum_zero_to_n」)。 – akaihola

+0

你知道這個值有一個封閉的表單解決方案嗎? 'InclusiveRange = lambda end:(end *(end + 1))/ 2' – lejlot

回答

1

從函數頭中刪除參數「end」並使用你的函數。

InclusiveRange() 

或定義代碼另一種方式:

def InclusiveRange(end):   
    while start <= end: 
      start += 1 
    print("The total of the numbers, from 0 to %d, is: %d" % (end, start)) 
end = int(input("Enter Variable: ") 
InclusiveRange(end) 
0

下面是一個itertools版本:

>>> from itertools import count, islice 
>>> def sum_to_n(n): 
...  return sum(islice(count(), 0, n + 1)) 
>>> 
>>> sum_to_n(int(input('input integer: '))) 
input integer: 5 
15 
0
  • 你應該把用戶輸入了功能,並改爲調用功能一旦你收到用戶輸入。
  • 您還需要將總和存儲在單獨的變量中才能啓動,否則每次迭代只會加1。 (在本例中,我將它重命名爲index,因爲它反映了它的用途)。

def InclusiveRange(end): 
    index = 0 
    sum = 0 
    while index <= end: 
     sum += start 
     index += 1 
    print("The total of the numbers, from 0 to %d, is: %d" % (end, sum)) 

end = int(input("Enter Variable: ")) 
InclusiveRange(end) 

Demo

0

而不是使用一個迴路,使用range對象,你可以輕鬆地發送到sum()。另外,你永遠不會使用傳遞的end變量,立即丟棄它並將end綁定到一個新的值。從函數外部傳入。

def inclusive_range(end): 
     num = sum(range(end+1)) 
     print("The total of the numbers, from 0 to {}, is: {}".format(end, num)) 

inclusive_range(int(input("Enter Variable: "))) 
0

你也可以使用一個math formula從1計算所有自然數的總和N.

def InclusiveRange(end): 
    ''' Returns the sum of all natural numbers from 1 to end. ''' 
    assert end >= 1 
    return end * (end + 1)/2 

end = int(input("Enter N: ")) 
print(InclusiveRange(end))