为什么我的递归函数返回None? [英] Why does my recursive function return None?

查看:94
本文介绍了为什么我的递归函数返回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",则一切正常:

Now, if I input just "a" or "b", everything works fine:

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

但是,如果我输入其他内容,然后输入"a"或"b",则会得到以下提示:

But, if I type something else and then "a" or "b", I get this:

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

I don't know why get_input() is returning None since it should only return my_var. Where is this None coming from and how do I fix my function?

推荐答案

它正在返回None,因为当您递归调用它时:

It is returning None because when you recursively call it:

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

..您不返回该值.

因此,尽管确实发生了递归,但返回值被丢弃,然后您脱离函数的结尾.掉到函数末尾意味着python隐式返回None,就像这样:

So while the recursion does happen, the return value gets discarded, and then you fall off the end of the function. Falling off the end of the function means that python implicitly returns None, just like this:

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

因此,您不仅需要在if语句中return调用,而且不仅仅是调用 get_input()

So, instead of just calling get_input() in your if statement, you need to return it:

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

这篇关于为什么我的递归函数返回None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆