2015-05-04 79 views
1
N = [] 
stop = 1 

while(stop != "0"): 
    number = input("Give a mark: ") 
    stop = raw_input("type 0 if you want to stop the program.") 
    N.append(number) 

print (float(sum(N)))/(len(N)) 

這是我的代碼。我想知道我給該計劃的平均分數。現在,我想這會工作,但它引發以下錯誤:如何獲得python列表中數字的總和?

TypeError: unsupported operand type(s) for +: 'int' and 'tuple' 

它使用float和所有其他類型的數字相同,我怎麼sopposed獲得這些商標的總和,如果我不能使用總和()?

+0

你的問題是太多的括號。只需使用print 1.0 * sum(N)/ len(N)'' – randomusername

+0

'N = [1,2,3]; print(float(sum(N)))/(len(N))'工作正常,不能重現。 –

+0

函數輸入的輸出是一個字符串,您將其存儲到列表中。首先將其轉換爲int,然後繼續。 – RvdK

回答

0

首先,你讀的是字符串,而不是數字,所以你必須先轉換它們。

N = [] 
stop = 1 

while(stop != "0"): 
    number = float(input("Give a mark: ")) 
    stop = raw_input("type 0 if you want to stop the program.") 
    N.append(number) 

print sum(N)/len(N) 

你得到的錯誤是因爲sum初始化爲0整數類型的變量,然後開始一個加入列表中的一個項目,因此它試圖將字符串添加到整數和。

+0

你的鑄造錯誤的價值。 (編輯你的答案) – RvdK

+0

沒錯。謝謝@RvdK –

+1

這實際上沒有什麼區別,雖然不是一個好的方法來做輸入會返回一個在Python 2中的float而不是一個字符串,但錯誤也與sum有關。 –

2

謝謝,我已經知道問題是什麼,我用例如2,0作爲浮點數,但它必須是2.0,但感謝您的幫助。

+0

如果使用輸入,你也應該使用'float(raw_input())'。 –