2013-03-20 41 views
-3

我已經在這個問題上取得了進展,但它總是返回僅列表中的第一個值。我在代碼中缺少什麼?Python幫助請 - 創建基本功能(Ver 2.7)

編寫一個名爲add_numbers的函數,它接收一個列表參數。它從頭開始返回列表中所有數字的總數,直到找到至少10個數字。如果找不到大於或等於10的數字,它將返回列表中所有數字的總和。

def add_numbers(a): 

total = 0 

i = 0 

    while a[i] < 10: 

    total = total + a[i] 

    i = i + 1 

    return total 

第二個是:

收件,接收一個數字參數的函數調用make_list。它返回一個從0到小於數字參數的數字列表。

我知道如何做到這一點,如果要求所有數字的總和,但我很困惑的名單。

最後一個是:

編寫一個叫做count_bricks接收一個數字參數的功能。這個函數返回一個金字塔裏很多層次磚頭的數量。金字塔中的每個層次都比上面的層次多一個磚塊。

不知道該從哪裏開始。

感謝您的幫助提前。這不是作業,它只是一個包含問題的抽樣測驗 - 這些是我無法回答的問題。

+4

請格式化您的問題中的代碼。我懷疑你的第一部分的問題與你的'return'語句的位置有關,但沒有格式化的代碼,很難說。另外,這功課呢? – That1Guy 2013-03-20 20:32:06

+0

請縮進您的代碼。 – 2013-03-20 20:33:04

+3

請一次提出一個問題。 – 2013-03-20 20:38:57

回答

2

您必須將循環放回循環外,否則該值將在第一次迭代時返回。

def add_numbers(a): 
    total = 0 
    i = 0 
    while a[i] < 10 and i < len(a): 
     total = total + a[i] 
     i = i + 1 
    return total  # return should be outside the loop 

提示關於第二個問題:

  1. 創建一個函數,它有一個輸入
  2. 返回使用內置函數range()一個新的列表。
+0

感謝你的 – 2013-03-20 20:42:36

0

第一個問題:

添加檢查結束循環,列表結束時:

while a[i] < 10 and i < len(a): 

問題二:

閱讀有關Python的lists。只需循環編號的次數並將該編號添加到列表中即可。最後返回該列表。

0
def add_numbers(a): 
    """ 
     returns the total of all numbers in the list from the start, 
     until a value of least 10 is found. If a number greater than 
     or equal to 10 is not found, it returns the sum of all numbers in the list. 
    """ 
    total = 0 
    index = 0 
    while index < len(a): 
     total = total + a[index] 
     if a[index] >= 10: 
      break 
     index += 1 
    return total