在Python中,如何在循环中获得总和和平均值
我成功地实现了一个循环,但在尝试在Python中,如何在循环中获得总和和平均值,python,loops,python-3.x,sum,average,Python,Loops,Python 3.x,Sum,Average,我成功地实现了一个循环,但在尝试sum函数时,一直出现语法错误。我需要由用户输入的数字进行合计,并给出平均值。这必须输出给用户。你能告诉我从这里到哪里去吗,谢谢。这就是我到目前为止所做的: while 1: NumCalc = input ("Enter Number :") if NumCalc == "done": break 如果要在循环结束后计算总和和平均值,可以执行以下操作: nums = [] while 1: NumCalc = input ("Enter
sum
函数时,一直出现语法错误。我需要由用户输入的数字进行合计,并给出平均值。这必须输出给用户。你能告诉我从这里到哪里去吗,谢谢。这就是我到目前为止所做的:
while 1:
NumCalc = input ("Enter Number :")
if NumCalc == "done": break
如果要在循环结束后计算总和和平均值,可以执行以下操作:
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
如果要在循环结束后计算总和和平均值,可以执行以下操作:
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
感谢您的帮助,但它不起作用这是我收到的输出我知道为什么吗?输入数字:5求和是:输入数字:6求和是:输入数字:完成>>@user3417793您的Python版本是什么?如果有帮助,这就是输出的外观我被告知输入值1:5输入值1:8输入值1:11输入值1:done谢谢你。总数:24平均数:8。0@user3417793我的错。我以为你在用蟒蛇。更新。感谢您的帮助。感谢您的帮助,但它不起作用。这是我收到的输出。知道原因吗?输入数字:5求和是:输入数字:6求和是:输入数字:完成>>@user3417793您的Python版本是什么?如果有帮助,这就是输出的外观,我被告知输入值1:5输入值1:8输入值1:11输入值1:完成,谢谢。总数:24平均数:8。0@user3417793我的错。我以为你在用蟒蛇。更新了。谢谢你的帮助