I want write a method that asks a user to input a digit, but if the user also inputs a string it needs to ask the user to input again until the correct data is input.
-------code that shows error-------------
def get_total():
try:
total = int(input("How many people you got in total: "))
except:
print("Your data is invalid, please try again.")
get_total()
return total
x = get_total()
print(x)
If you type 5
directly, it will print 5
.
However if you type "s
" first and then 5
, it will throw this error:
"local variable 'total' referenced before assignment"
Can anyone could please tell me why?
If I correct the code like this, it works just fine
------code that works fine-----------------
def get_total():
try:
total = int(input("How many people you got in total: "))
return total
except:
print("Your data is invalid, please try again.")
return get_total()
x = get_total()
print(x)
So why does this happen?