我有一个函数调用它自己:
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
是从哪里来的,我如何修复我的函数?
要返回“无”以外的值,需要使用return语句。
在您的情况下,if块只在执行一个分支时执行一个返回。将返回移到if/else块之外,或者在两个选项中都有返回。
它返回
None
,因为当您递归调用它时:…你不返回值。
因此,当递归确实发生时,返回值被丢弃,然后从函数的末尾掉下来。从函数末尾脱落意味着python隐式返回
None
,如下所示:因此,在您的},而不是只调用:
if
语句中,您需要return
调用{相关问题 更多 >
编程相关推荐