本文介紹了在 Python 中,如何在循環中獲取總和和平均值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我已經設法實現了一個循環,但是當我嘗試 sum
函數時不斷收到語法錯誤.我需要匯總用戶輸入的數字并給出平均值.這必須輸出給用戶.您能否指導我從這里去哪里,謝謝.
這是我到目前為止所做的:
I've managed to implement a loop but keep getting a syntax error when I try the sum
function. I need the numbers input by the user to be totalled and the average given as well. This has to be outputted to the user. Could you please guide me on where to go from here, thank you.
This is what I've done so far:
while 1:
NumCalc = input ("Enter Number :")
if NumCalc == "done": break
推薦答案
如果您想在循環結束后計算總和和平均值,您可以這樣做:
This is what you can do if you want to compute the sum and the mean after the loop ends:
nums = []
while 1:
NumCalc = input ("Enter Number:")
if NumCalc == "done": break
nums.append(float(NumCalc))
print('Sum:', sum(nums), 'and average:', sum(nums)/len(nums))
<小時>在循環中:
s = 0.0
counter = 0
while 1:
NumCalc = input("Enter Number: ")
if NumCalc == "done":
break
NumCalc = float(NumCalc)
s += NumCalc
counter += 1
print('Sum is', s, 'and the mean is', s/counter)
輸出:
Enter Number: 5
Sum is 5.0 and the mean is 5.0
Enter Number: 2
Sum is 7.0 and the mean is 3.5
Enter Number: 4
Sum is 11.0 and the mean is 3.66666666667
Enter Number: 6
Sum is 17.0 and the mean is 4.25
Enter Number: 2
Sum is 19.0 and the mean is 3.8
這篇關于在 Python 中,如何在循環中獲取總和和平均值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!