def getNonNegNum(first,last): '''first and last are ints >= 0, where last >= first. Input from the user an int between first and last, inclusive. if the entered value is valid, return it. Otherwise, print an error message, and Return -1. ''' msg = "Enter an int between " + str(first) msg += " and " + str(last) + " " try: # This will cause a ValueError exception if the value # cannot be converted into an int ans = int(input(msg)) # Throw an exception if the value is not in range (this is a trick) if (ans < first or ans > last): 5/0 #This will be executed only if no exception is raised return ans except ValueError: print("The value must be an int") return -1 except ZeroDivisionError: print("The number must be between",first,"and",last) return -1 def main(): first = 10 last = 20 # test cases that must be tried: # general positive case: 15 # a non-int, like jjjj # a non-int num, like 4.2 # a negative number, say -45 # the value indicating an error, -1 (very important!) # a smaller number, 5 # a larger number, 25 # numbers just outside the boundaries: 9, 21 # numbers on the boundaries: 10, 20 ans = getNonNegNum(first,last) while ans == -1: ans = getNonNegNum(first,last) print("Finally, we have a valid answer:",ans) main()