2016-08-11 48 views
-5

如何完成我的程序,該程序重複讀取數字,直到用戶輸入 「完成」。輸入「完成」後,打印數字的總數,計數和平均值。如果用戶輸入除數字以外的任何內容,則使用try和except檢測他們的錯誤 並打印錯誤消息並跳到下一個數字。Python中的字符串,Int差異化和循環

count = 0 
total = 0 

while True: 
    x = raw_input('Enter number') 
    x=int(x) 
    total = total + x 
    count = count + 1 
    average = total/count 
    print total, count, average 
+1

你甚至嘗試使用異常搭上整數轉換錯誤?正如我所看到的,你真正需要做的只是在最後一行的unindent中添加「done」檢查和異常。 –

+0

再次嘗試並向我們展示更多努力 – Raskayu

+1

以'python'和'例外'開始搜索 –

回答

0

下面的代碼應該是你想要的。

count = 0 
total = 0 

while True: 
    x = raw_input('Enter number: ') 
    if(x.lower() == "done"): 
     break 
    else: 
     try: 
      x=int(x) 
      total = total + x 
      count = count + 1 
      average = total/count 
     except: 
      print("That is not an integer. Please try again.") 

print total, count, average 

或在Python 3

count = 0 
total = 0 

while True: 
    x = input('Enter number: ') 
    if(x.lower() == "done"): 
     break 
    else: 
     try: 
      x=int(x) 
      total = total + x 
      count = count + 1 
      average = total/count 
     except: 
      print("That is not an integer. Please try again.") 

print(total, count, average)