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)) except ValueError: print("The value must be an int") return -1 # If we are still here, we know that ans is a valid int. # Otherwise, we would have returned -1 if (ans < first or ans > last): print("The number must be between",first,"and",last) return -1 return ans 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()