# Program to show interactive while loop with a nested loop # Matt Bishop, May 4, 2009 # for ECS 10 Spring 2009 import string # 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 != "": # now break line into individual numbers linelist = string.split(line) for i in linelist: try: sum += int(i); 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()