为什么我的递归python函数不返回?我有一个叫做自己的函数: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_varprint('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我是从哪里来的,我该如何修复我的功能?
4 回答
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
None
if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input()
None
>>> def f(x):... pass>>> print(f(20))None
get_input()
if
return
if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') return get_input()
汪汪一只猫
TA贡献1898条经验 获得超8个赞
慕丝7291255
TA贡献1859条经验 获得超6个赞
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_varprint('got input:', get_input())
波斯汪
TA贡献1811条经验 获得超4个赞
if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input()
get_input
else: return my_var
print('got input:', get_input())
while my_var!="a" and my_var!="b": print('You didn\'t type "a" or "b". Try again.') return get_input()
添加回答
举报
0/150
提交
取消