# 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 while True: # 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 break except (NameError, TypeError, SyntaxError): # non-number entered; complain print "You did not enter a number" else: # got a number break # once you get a number, return it return n # computes an average def main(): sum = 0 count = 0 # go until user says enough while True # get input number n = readnum() # if the sentinel, drop out if n == -9999: break: # add number, increment count sum += n; count += 1 # print average if (count > 0): print "The average of the", count, "numbers you entered is", float(sum)/count else: print "No numbers entered!" main()