首页 >后端开发 >Python教程 >为什么我的递归输入验证函数不返回任何内容?

为什么我的递归输入验证函数不返回任何内容?

Susan Sarandon
Susan Sarandon原创
2025-01-04 21:52:40787浏览

Why Does My Recursive Input Validation Function Return None?

为什么我的递归函数似乎返回 None?

考虑一个验证用户输入的递归函数:

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())

如果用户输入“a”或“b”,一切都会按预期进行。但是,如果用户最初输入无效输入然后进行更正,则该函数似乎返回 None 而不是用户的输入。

这种不稳定的行为源于递归分支中的疏忽。当函数再次正确调用自身时,它无法返回递归调用的结果:

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

要解决此问题,我们需要返回从递归调用获得的值:

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

此更改可确保函数正确地向下级联递归堆栈,返回正确的用户输入。

# 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())

通过此修改,即使在处理无效输入后,该函数也将正确返回用户的输入。

以上是为什么我的递归输入验证函数不返回任何内容?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn