Cat*_*ate 46 python recursion return 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.')
        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.print语句显示None正确的值,但函数由于某种原因不返回该值.
roi*_*ppi 68
它正在返回,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
因此,您需要这样做,而不仅仅是在您的声明中调用 .get_input()ifreturn