I have a piece of code to ask a user for a number within a certain range. I know what works, in part from looking at questions like this: Limiting user input to a range in Python
In playing with it, though, I made the function below, which works in all cases except when there's text entered at any point prior to a correct entry. For example, inputting 3, 2, f, 3, 2, 5
produces the following:
TypeError: '<=' not supported between instances of 'int' and 'str'
In all other cases the code works.
Code:
def pick_a_number():
user_number = input("Pick a number from 5 to 10, inclusive. ")
try:
user_number = int(user_number)
except:
print("Not a valid entry. Try again. ")
pick_a_number()
if 5 <= user_number <= 10:
print("You picked " + str(user_number))
else:
print("Number out of range. Try again.")
pick_a_number()
pick_a_number()
Why does the code fail the way that it does? I think it's something to do with the repeated calls to the function within the function, but I'd like to understand what's happening.