Shawn
Shawn

Reputation: 13

I am trying to make a program that calculates the average, maximum, and minimum? Python

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

Upvotes: 0

Views: 1091

Answers (3)

Martin Ogden
Martin Ogden

Reputation: 882

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

Upvotes: 1

David Chan
David Chan

Reputation: 7505

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)

Upvotes: 0

frans
frans

Reputation: 9758

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.

Upvotes: 0

Related Questions