python求平均值while_在Python中,如何在循环中获取总和和平均值

1586010002-jmsa.png

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))

While in a loop:

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)

Output:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值