Python 具有相同参数的递归函数
我正在用python创建一个基于文本的游戏,遇到了一个障碍。我有一个函数,检查用户输入是否包含某些单词,如果包含,则返回用户输入,否则将重新请求输入。如果您编写的内容不包含其中一个单词,它将重新调用该函数Python 具有相同参数的递归函数,python,user-input,text-based,Python,User Input,Text Based,我正在用python创建一个基于文本的游戏,遇到了一个障碍。我有一个函数,检查用户输入是否包含某些单词,如果包含,则返回用户输入,否则将重新请求输入。如果您编写的内容不包含其中一个单词,它将重新调用该函数 def contains_words(prompt, words): user_input = raw_input(prompt).strip().lower() if user_input == "instructions": print
def contains_words(prompt, words):
user_input = raw_input(prompt).strip().lower()
if user_input == "instructions":
print
instructions()
print
contains_words(prompt, words)
elif user_input == "i" or user_input == "inventory":
if len(inventory) == 0:
print
print "There is nothing in your inventory."
print
contains_words(prompt, words)
else:
print "Your inventory contains: " + inventory
contains_words(prompt, words)
else:
if user_input in words:
return user_input
else:
print
print "I did not understand your answer, consider rephrasing."
contains_words(prompt , words)
我叫它:
pizza = contains_words("Do you like pizza?", ["yes", "no"])
在该功能中,您可以调出说明或库存,然后它将调用该功能。如果你在第一次被问到的时候把其中一个词放在你的答案里,一切都会正常进行。当您输入不正确的内容、调出清单或调出说明时,就会出现问题。它使函数不返回任何内容,而不是用户输入。为什么会这样?是因为函数重置,所以参数等于none吗 您只需将代码中的语句
包含单词(提示,单词)
替换为返回包含单词(提示,单词)
当您递归时,您需要返回结果
return contains_words(prompt , words)
让我们看一下这个函数的一个示例调用
pizza = contains_words("Do you like pizza?", ["yes", "no"])
说出用户输入的说明
。如果第一个语句是True
,那么我们进入该块,将调用instructions()
(可能是将指令打印到控制台),并且再次调用包含单词的。假设用户这次输入了yes
。我们将继续讨论最后一个if
语句,它将是True
,而这个调用包含
将返回yes
--到它被调用的位置
现在,我们将堆栈备份到原始调用contains\u words
。返回值被忽略,因为函数本身在一行上被调用,而不是作为另一个函数或语句的参数。现在我们已经完成了这个if
块,函数中的下一件事是。。。没有什么。其余的if
selif
s和else
s没有任何意义(因为原始if
计算为True
),我们从函数底部退出。它不返回任何内容(实际上是None
)。(检查比萨饼的类型以查看。)
解决方案是将递归调用更改为return contains_words(prompt,words)
,这样当函数从每个递归调用中退出时,它会将返回值传递到堆栈中,或者,因为这只是尾部递归,所以用循环替换它:
def contains_words(prompt, words):
while True:
user_input = raw_input(prompt).strip().lower()
if user_input == "instructions":
print
instructions()
print
elif user_input == "i" or user_input == "inventory":
if len(inventory) == 0:
print
print "There is nothing in your inventory."
print
else:
print "Your inventory contains: " + inventory
else:
if user_input in words:
return user_input
else:
print
print "I did not understand your answer, consider rephrasing."
这将避免可能涉及许多递归的内存问题。(a)您能纠正缩进吗?在代码块中使用ctrl+k,用于(b)为什么在不同的位置调用方法包含单词和不包含self
?所有递归调用都需要返回结果<代码>返回包含单词(提示,单词)
自我是一个意外事件。Removing这背后的原因是什么?如果你不返回任何内容,函数会隐式返回None
,但你说它应该返回用户输入。这背后的原因是什么?