提问者:小点点

为什么我的递归函数返回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()
    else:
        return my_var

print('got input:', get_input())

现在,如果我只输入“a”或“b”,一切都正常:

Type "a" or "b": a
got input: a

但是,如果我输入其他内容,然后输入“a”或“b”,就会得到:

Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None

我不知道为什么get_input()返回none,因为它应该只返回my_var。 这个none从何而来,我如何修复我的函数?


共3个答案

匿名用户

它返回none,因为当您递归调用它时:

if my_var != "a" and my_var != "b":
    print('You didn\'t type "a" or "b". Try again.')
    get_input()

你。。。不返回值。

所以当递归发生时,返回值会被丢弃,然后你会从函数的末尾掉下来。 函数末尾脱落意味着python隐式返回none,就像这样:

>>> def f(x):
...     pass
>>> print(f(20))
None

因此,不只是在if语句中调用get_input(),您需要返回它:

if my_var != "a" and my_var != "b":
    print('You didn\'t type "a" or "b". Try again.')
    return get_input()

匿名用户

若要返回除None以外的值,需要使用return语句。

在您的示例中,if块仅在执行一个分支时执行一个返回。 要么将返回移动到if/else块之外,要么在两个选项中都有返回。

匿名用户

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()
    else:
        return my_var

print('got input:', get_input())