# Program to add scores in a file, prettyprint the lines, and # compute and print the average # Name of file is "scores.txt" in current working directory # Format of file: each line has a name, a blank, and an integer score; example: # Tom 30 # Dick 100 # ... # Matt Bishop, Apr. 27, 2009 # for ECS 10 Spring 2009 import string; # this routine splits a line into the name and the score # parameters: line, the input line # returns: the score # side effect: prints the input line in a nice way def format(line): # separate the line into two parts at the blank fields = string.split(line, " "); # convert the second field to an int (it's a string from the above line) fields[1] = int(fields[1]); # prettyprint the line, so the names line up, and the scores line up print "%-13s %4d" % ( fields[0] , fields[1] ); # return the score return fields[1]; # this routine manages the score file and builds a list of scores # returns: a list of scores as integers # calls: format: parse line, prettyprint it, and return score from it def readscores(): # open the file containing scores scoref = open("scores.txt", "r"); # initialize the list of scores scores = []; # read and process each line for line in scoref: # get the score (and prettyprint the line) grade = format(line); # add score to list scores = scores + [ grade ]; # close the file containing scores scoref.close(); return scores; # this routine computes the average of a list of integers # returns: the average of the numbers in the list def average(scores): # initialize the sum sum = 0; # add the numbers in the list for i in scores: sum += i; # compute the average return sum / len(scores); # now put it all together # calls: readscores: prints lines and returns list of scores found # average: compute average of a list of numbers def main(): # read in the scores, and prettyprint the lines listscores = readscores(); # print the average print "Average score: %3d" % average(listscores); main();