问:
我有一个调用自己的函数:
代码语言:javascript复制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",一切都会正常运行:
代码语言:javascript复制Type "a" or "b": a
got input: a
但是,如果我输入别的东西,然后输入 "a" 或 "b",我会得到这样的结果:
代码语言:javascript复制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 是从哪里来的?我该如何修复我的函数呢?
答:
它返回 None 是因为当你递归调用它时:
代码语言:javascript复制if my_var != "a" and my_var != "b":
print('You didn't type "a" or "b". Try again.')
get_input()
.. 没有返回那个值。
因此,尽管递归确实发生了,但返回值却被丢弃了,然后你会从函数末尾退出。在函数末尾退出意味着 Python 会隐式地返回 None,就像下面这样:
代码语言:javascript复制>>> def f(x):
... pass
>>> print(f())
None
In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name). Python3 documentation
因此,除了在 if 语句中调用 get_input() 之外,还需要返回递归调用返回的内容。get_input() 函数可以按如下两种方式修复:
代码语言:javascript复制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
或者
代码语言:javascript复制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.')
my_var = get_input()
return my_var
=====
参考文档:
- stackoverflow question 17778372
- https://docs.python.org/3/tutorial/controlflow.html#defining-functions