Why does my recursive function appear to return None?
Consider a recursive function that validates user input:
def get_input(): my_var = input('Enter "a" or "b": ') if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input() # Recursively call the function else: return my_var print('got input:', get_input())
If the user enters "a" or "b," everything works as expected. However, if the user initially enters an invalid input and then corrects it, the function appears to return None instead of the user's input.
This erratic behavior stems from an oversight in the recursive branch. While the function correctly calls itself again, it fails to return the result of the recursive call:
if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input() # This line should be replaced
To fix this, we need to return the value obtained from the recursive call:
if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') return get_input() # We return the result of the recursive call
This change ensures that the function properly cascades down the recursive stack, returning the corrected user input.
# Modified function def get_input(): my_var = input('Enter "a" or "b": ') if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') return get_input() # We return the result of the recursive call else: return my_var print('got input:', get_input())
With this modification, the function will correctly return the user's input, even after handling invalid inputs.
The above is the detailed content of Why Does My Recursive Input Validation Function Return None?. For more information, please follow other related articles on the PHP Chinese website!