我设法实现循环,但在尝试sum
函数时不断出现语法错误。我需要用户输入的数字进行总计并给出平均值。这必须输出给用户。你能指导我从哪里开始,谢谢你。
这是我到目前为止所做的:
while 1:
NumCalc = input ("Enter Number :")
if NumCalc == "done": break
答案 0 :(得分: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))
<小时/> 在循环中 while :
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
答案 1 :(得分: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