0

I have figured out how to make it find the maximum and minimum but I cannot figure out the average. Any help will be greatly appreciated.

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shawn
  • 13
  • 1
  • 4

3 Answers3

1

If you keep track of the amount of numbers entered and also the sum of all the numbers entered then you can calculate the average. 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
Martin Ogden
  • 872
  • 4
  • 14
0

This answer (I've searched about 1sec) gives me

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

for arbitrary lists.

Community
  • 1
  • 1
frans
  • 8,868
  • 11
  • 58
  • 132
0

in order to calculate the average also called the mean you need to keep a running list of the numbers you've collected.

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)
David Chan
  • 7,347
  • 1
  • 28
  • 49