Home > Backend Development > Python Tutorial > Why Does My Recursive Input Validation Function Return None?

Why Does My Recursive Input Validation Function Return None?

Susan Sarandon
Release: 2025-01-04 21:52:40
Original
724 people have browsed it

Why Does My Recursive Input Validation Function Return None?

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())
Copy after login

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
Copy after login

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
Copy after login

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())
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template