在Python中,如何在循环中获取和与平均值
我已经成功写了一个循环,但每次我尝试使用sum
函数时,总是出现语法错误。我需要用户输入的数字进行求和,并计算出平均值。最后,这些结果需要显示给用户。你能帮我看看接下来该怎么做吗,谢谢。
这是我到目前为止所做的:
while 1:
NumCalc = input ("Enter Number :")
if NumCalc == "done": break
2 个回答
1
在编程中,有时候我们需要把一些数据从一个地方转移到另一个地方。这就像把水从一个杯子倒到另一个杯子一样。这个过程可能会涉及到不同的步骤,比如选择要转移的数据、确定目标位置等等。
有些时候,数据的格式可能会不一样,就像不同的杯子可能有不同的形状和大小。这时候,我们需要确保在转移数据时,不会让它们变得混乱或者丢失。
此外,转移数据的速度也很重要。就像你希望水能快速流动,而不是慢慢滴下来一样。在编程中,我们也希望数据能快速有效地转移。
总之,数据转移是编程中一个常见的任务,理解这个过程能帮助我们更好地处理信息。
i = 0
sum = 0
while 1:
i += 1
NumCalc = input ("Enter Number :")
if NumCalc == "done": break
sum = sum + NumCalc
print "Average is ", sum/i
3
如果你想在循环结束后计算总和和平均值,可以这样做:
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