为什么递归python函数不返回?

2024-05-16 01:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数调用它自己:

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是从哪里来的,我如何修复我的函数?


Tags: ornoneyouinputget键入varmy
3条回答

要返回“无”以外的值,需要使用return语句。

在您的情况下,if块只在执行一个分支时执行一个返回。将返回移到if/else块之外,或者在两个选项中都有返回。

它返回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语句中,您需要return调用{},而不是只调用:

if my_var != "a" and my_var != "b":
    print('You didn\'t type "a" or "b". Try again.')
    return get_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.')
        return get_input()
    else:
        return my_var

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

相关问题 更多 >