本文介紹了在 Python 中,如何在循環(huán)中獲取總和和平均值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我已經(jīng)設(shè)法實現(xiàn)了一個循環(huán),但是當(dāng)我嘗試 sum
函數(shù)時不斷收到語法錯誤.我需要匯總用戶輸入的數(shù)字并給出平均值.這必須輸出給用戶.您能否指導(dǎo)我從這里去哪里,謝謝.
這是我到目前為止所做的:
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
推薦答案
如果您想在循環(huán)結(jié)束后計算總和和平均值,您可以這樣做:
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))
<小時>在循環(huán)中:
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
這篇關(guān)于在 Python 中,如何在循環(huán)中獲取總和和平均值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!