我有一个函数,它调用自己:
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
从何而来,我如何修复我的函数?
它返回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
语句中调用get_input()
,您需要返回
它:
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
return get_input()
若要返回除None以外的值,需要使用return语句。
在您的示例中,if块仅在执行一个分支时执行一个返回。 要么将返回移动到if/else块之外,要么在两个选项中都有返回。
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())