Welcome, guest | Sign In | My Account | Store | Cart

One program that a teacher may assign to beginning programming students would be to take a list of numbers and average them together. This recipe does just that and is designed to be easy to read and follow, showing what is possible with a few lines of Python.

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import ast

while True:
    try:
        string = raw_input('What numbers should I average? ')
        words = string.split()
        numbers = [ast.literal_eval(word) for word in words]
        total = sum(numbers)
        count = len(numbers)
        average = 1.0 * total / count
        print 'The average is', average
        raw_input('Press enter to quit.')
        break
    except:
        print 'Please only give me numbers.'