# Program to read in a positive number # and complain when the input isn't that # Matt Bishop, February 23, 2012 # ECS 10, Winter 2012 # read in a positive number # raise a ValueError if input is def getposnumber(): # read the input and convert it to an integer # notice we do *not* catch the error here; it # is to be caufht by the caller instr = input("type a number: ") n = int(instr) # # okay, it's an int -- f it's a nonpositive one, complain # if n < 0: raise ValueError("You entered a negative number") elif n == 0: raise ValueError("You entered 0") # # now just return it # return n # # the program itself # def main(): # # loop to show how to break out of an infinite loop # while True: # # read in a positive nteger # handle any exceptions (relatively) intelligently # try: n = getposnumber() # first exception: bad value (string, invalid number) except ValueError as msg: print(msg) print("You need to enter a positive number") # next exception: user typed EOF, so leave loop except EOFError as msg: print(msg, "-- bye!") # say bye! break # no exception -- print the number else: print("Read", n) finally: print("\n-----------------------\n") main()