# Program to show interactive while loop # Matt Bishop, May 4, 2009 # for ECS 10 Spring 2009 # reads a number and makes sure it is a number # return the sentinel, -9999 on end of file def readnum(): # we loop until we find a number isnum = "no" while isnum == "no": # now we read a number, looking for bogus input try: n = input("Enter number (-9999 to quit): ") # this raises an exception if it's not a number n += 0 except EOFError: # end of file found; quit gracefully n = -9999 isnum = "yes" except (NameError, TypeError, SyntaxError): # non-number entered; complain print "You did not enter a number" else: # got a number isnum = "yes" # once you get a number, return it return n # computes an average def main(): sum = 0 count = 0 # go until user says enough n = readnum() while n != -9999: # add number, increment count sum += n; count += 1 # get next number n = readnum() # print average if (count > 0): print "The average of the", count, "numbers you entered is", float(sum)/count else: print "No numbers entered!" main()