python - 递归调用导致类函数中的 IndexError
问题描述
我的程序的目标是让计算机向用户提出问题,并返回一些符合他们需求的计算机规格。现在我正在研究 QuestionAsker,顾名思义,它负责向用户提问。我一直挂在 AskQuestion() 函数的第 4 行。在我告诉你问题之前,先看一下代码:
from question import Question
class QuestionAsker():
questions = [
Question("At minimum, what should your game be running on?", ["Low", "Medium", "Ultra"]),
Question("On a scale of 1-3, how much flair do you want on your computer?", ["Low", "Medium", "Ultra"]),
Question("Money doesn't grow on trees. How much money is in your budget?", ["$500", "$1000", "$2000+"]),
]
index = 0
def AskQuestion(self):
userInputForQuestion = raw_input(self.questions[self.index].question + " ")
if userInputForQuestion not in self.questions[self.index].answers:
print("Try again.")
self.AskQuestion()
self.questions[self.index].selectedAnswer = userInputForQuestion
self.index += 1;
def resetIndex(self):
self.index = 0
def ReadQuestions(self):
pass
我通过调用 AskQuestion 几次来测试这段代码(循环遍历所有问题),并确保这段代码是最重要的,我提供了多个返回“再试一次”的答案,因为它应该。问题是,如果我对一个问题提供了超过 1 个错误答案,但如果我在多个错误答案后正确回答,我会收到以下错误消息:
IndexError: list index out of range
我立即怀疑是[self.index]
,self.questions[self.index]
所以我开始将索引打印到控制台。我认为问题在于 AskQuestion 在 AskQuestion 函数的最后一行神奇地增加了 self.index,但不是。它一直打印一个一致的数字,在第一个问题的情况下,0!
我在这里束手无策,我在这方面看到的其他问题并没有太大帮助。希望各位大神帮忙,谢谢!
解决方案
请注意,在您的函数体中,当给出错误答案时,函数不会结束。它进行递归调用。当该调用结束时,索引仍会递增。所以错误的答案仍然会弄乱索引。
您应该在进行错误调用后结束该函数,以实现您想要发生的事情。
if userInputForQuestion not in self.questions[self.index].answers:
print("Try again.")
self.AskQuestion()
return None
或使用else
.
if userInputForQuestion not in self.questions[self.index].answers:
print("Try again.")
self.AskQuestion()
else:
self.questions[self.index].selectedAnswer = userInputForQuestion
self.index += 1;
另请注意,以这种方式使用递归并不常见。无论如何,这使您犯了错误。
推荐阅读
- spring - JUnit Test 错误地传递了错误的参数
- amazon-web-services - 使用 AWS 网关的 API 版本控制(非 lambda 函数)
- halide - 如何通过 JIT 在 Halide 中使用 define_extern?
- python - 如何从 python 调用中获取命令 docker shell 提示符
- android - Android、Tomcat 和 Postman:捕获 HTTP 请求
- vba - 执行 vba 查询 ms 访问时出现运行时错误 3075
- webpack - 纱线安装失败,模块解析失败:意外字符“@”(1:0)
- python - 我的字符串和变量不能在这个 tkinter 函数中一起工作?
- code-coverage - AOSP 本机代码覆盖率 - 未找到覆盖率数据
- xampp - 在打开文件时使用 PhpStorm XAMPP 它使用端口 63442 而不是默认端口,我该如何更改它?