# Program to show interactive while loop # Matt Bishop, May 4, 2009 # for ECS 10 Spring 2009 # computes an average def main(): # initialize sum = 0 count = 0 # get file name and open file try: inname = raw_input("Enter file name: ") infile = open(inname, "r") except EOFError: # exit return except IOError as detail: # couldn't open the file print detail return # if we get here, we have the file opened # read in its contents line = infile.readline() # process each line while line != "": # add number, increment count try: sum += int(line); except ValueError: # not a number on the line print "Invalid number \"%s\"" % line else: # it worked; one more number count += 1 # get next number line = infile.readline() # print average if count > 0: print "The average of the", count, "numbers you entered is", float(sum)/count else: print "No numbers entered!" main()