2016-03-01 38 views
0

我正在編寫用於從輸入創建一個數字列表並獲取列表的平均值。要求是:當用戶輸入一個號碼時,該號碼將被追加到列表中;當用戶按Enter時,輸入部分將停止並執行計算部分。 這裏是我的代碼:在python中使用輸入3

n = (input("please input a number")) 
numlist = [] 

while n != '': 
    numlist.append(float(n)) 
    n = float(input("please input a number")) 

    N = 0 
    Sum = 0 
    for c in numlist: 
     N = N+1 
     Sum = Sum+c 

Ave = Sum/N 
print("there are",N,"numbers","the average is",Ave) 

,如果我輸入數字,一切工作正常。但是當我按Enter時,它顯示ValueError。我知道問題出在float()。我該如何解決這個問題?

+0

第一個'N'仍然是一個字符串添加一個嘗試,catch塊。 – bereal

+0

在while循環中追加期間,第一個n被轉換爲numlist.append()中的浮點數。我剛剛刪除了第二個n的float轉換,並且它工作。 – rogerc1992

+1

當您按Enter鍵時,輸入無法轉換爲浮點數,並且正確顯示數值錯誤。您可以保存輸入結果並在嘗試將其轉換爲浮點形式之前對其進行檢查,或者可以使用try/catch塊來捕獲異常並計算平均值。除此之外,我甚至無法開始計算您在這樣一個小代碼片段中遇到的問題。 – Muposat

回答

2

,因爲你叫float()當你追加nnumlist你不需要繞input()功能float()你的循環中。

-1

這應該解決UR的概率,由烏爾左右print語句

n = (input("please input a number")) 
numlist = [] 

while True : 
    numlist.append(float(n)) 
    #####cath the exception and break out of 
    try : 
     n = float(input("please input a number")) 
    except ValueError : 
     break 


N = 0 
Sum = 0 
for c in numlist: 
    N = N+1 
    Sum = Sum+c 



Ave = Sum/N 
print("there are",N,"numbers","the average is",Ave) 
+0

爲什麼不必要地調用'float()'兩次? – tjohnson