我有一个函数询问问题并进行比较,如果不匹配"yes",它会调用自己再次询问问题。问题是,当函数第二次被调用时,它会返回旧值。
def question():
ask = input("Are you OK?:").lower()
if ask != 'yes':
question()
return ask
print (question())
#output:
Are you OK?:no
Are you OK?:no
Are you OK?:yes
no
Process finished with exit code 0
我尝试了不同的方法,添加了elif,但没有返回任何结果,所以我想到了另一个想法,使用嵌套函数和参数,也没有预期的结果。
def question():
ask = input("Are you OK?:").lower()
def check_question(n):
if ask != 'yes':
question()
else:
return ask
m = check_question(ask)
print (m)
question()
#output:
Are you OK?:no
Are you OK?:yes
None
Process finished with exit code 0
正如我在评论中所说,这不是一个很好的递归候选者。你只需要一个简单的while循环:
ask='no'
while ask != 'yes':
ask = input("Are you OK? ").lower()