我正在尝试制作一个计算平均值,最大值和最小值的程序?蟒蛇

时间:2014-11-13 22:44:11

标签: python

我已经想出如何让它找到最大值和最小值,但我无法弄清楚平均值。任何帮助将不胜感激。

minimum=None
maximum=None

while True:
    inp= raw_input("Enter a number:")
    if inp == 'done':
        #you must type done to stop taking your list
        break

    try:
        num=float(inp)
    except:
        print 'Invalid input'
        continue

    if minimum is None or num<minimum:
        minimum = num

    if maximum is None or num>maximum:
        maximum = num

print "Maximum:", maximum
print "Minimum:", minimum

3 个答案:

答案 0 :(得分:1)

如果您跟踪输入的数字量以及输入的所有数字的总和,则可以计算平均值。 e.g:

n = 0  # count of numbers entered
s = 0.0  # sum of all numbers entered

while True:
    inp = raw_input("Enter a number:")

    try:
        num = float(inp)
    except:
        print 'Invalid input'
        continue

    n += 1
    s += num

    print "Average", s / n

答案 1 :(得分:0)

This回答(我搜索了大约1秒钟)给了我

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l) / len(l)

任意列表。

答案 2 :(得分:0)

为了计算平均值,也称为平均值,您需要保留已收集的数字的运行列表。

nums = []

while True:
    inp= raw_input("Enter a number:")
    if inp == 'done':
        #you must type done to stop taking your list
        break

    try:
        num=float(inp)
        nums.append(num)
    except:
        print 'Invalid input'
        continue

    if minimum is None or num<minimum:
        minimum = num

    if maximum is None or num>maximum:
        maximum = num

print "Maximum:", maximum
print "Minimum:", minimum
print "Average:", sum(nums)/len(nums)