为什么我的递归函数返回 Nothing?

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

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

121654 次浏览

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

..you don't return the value.

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

So, instead of just calling get_input() in your if statement, you need to return what the recursive call returns:

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

To return a value other than None, you need to use a return statement.

In your case, the if block only executes a return when executing one branch. Either move the return outside of the if/else block, or have returns in both options.

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

i think this code more clearly

def get_input():
my_var = str(input('Enter "a" or "b": '))
if my_var == "a" or my_var == "b":
print('got input:', my_var)
return my_var
else:
print('You didn\'t type "a" or "b". Try again.')
return get_input()
get_input()