如何计算python 2.7的平均值/平均值

时间:2015-03-26 18:28:04

标签: python-2.7 average

我试图计算用户输入数字时的平均值,并在他决定时停止。我设法获得总和然而我不能分割它因为我需要在他停止进入之前以某种方式获得输入的数量。到目前为止,这是我的代码:

print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")

s = 0

x = raw_input ('please enter the number')

while (num != 'f'):
    x = eval (x)
    s = s + x
    x = raw_input ('please enter the number')

print (' the average is'), s

就像你看到我设法获得总和但是我不知道如何获得输入的数量然后将总和除以得到平均值。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您只需在while循环中添加一个计数器:

print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")

s = i = 0         #declare counter: i = 0

x = raw_input ('please enter the number')

while (x != 'f'):
    x = eval (x)
    s = s + x
    i+=1          #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
    x = raw_input ('please enter the number')

print (' the average is'), s/i    #divide the sum by counter