def my_function():
try:
number = int(input("What is your favorite number?\n\n"))
except ValueError: #if anything but an integer was given as the str to input
my_function() #recursive to ask again
return number
my_function()
This throws the exception UnboundLocalError: local variable 'number' referenced before assignment
if I go through the recursive scope at least once and then give a valid input. I thought the variable number should point to a different object every iteration of the function. What am I missing here?
I recognize I can simply move return number
into the try
block to achieve this functionality, but why do I have to?