Python 类函数中导致索引器的递归调用
我的程序的目标是让计算机向用户提问,并返回一些适合他们需要的计算机规格。现在我正在研究QuestionAsker,正如类名所示,它负责向用户提问。我挂断了AskQuestion()函数的第四行。在我告诉您问题之前,请看一下代码:Python 类函数中导致索引器的递归调用,python,class,oop,recursion,Python,Class,Oop,Recursion,我的程序的目标是让计算机向用户提问,并返回一些适合他们需要的计算机规格。现在我正在研究QuestionAsker,正如类名所示,它负责向用户提问。我挂断了AskQuestion()函数的第四行。在我告诉您问题之前,请看一下代码: from question import Question class QuestionAsker(): questions = [ Question("At minimum, what should your game be running
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来测试这段代码(循环所有问题),为了确保这段代码是tippy top,我提供了多个答案,返回“重试”,这是应该的。问题是,如果我对一个问题提供了不止一个错误答案,但如果我在多个错误答案后回答正确,我会得到以下错误消息:
IndexError: list index out of range
我立即怀疑self.questions[self.index]
的[self.index]
,所以我开始将索引打印到控制台上。我认为问题在于AskQuestion在AskQuestion函数的最后一行神奇地增加了self.index,但是没有。它一直在打印一个一致的数字,对于第一个问题,0
我在这里束手无策,我在这方面看到的其他问题也没什么帮助。希望你们能帮忙,谢谢 请注意,在函数体中,当给出错误答案时,函数不会结束。它进行递归调用。当该调用结束时,索引仍然递增。因此,错误的答案仍然会把索引搞得一团糟 你应该在错误的调用后结束函数,因为你想发生什么
if userInputForQuestion not in self.questions[self.index].answers:
print("Try again.")
self.AskQuestion()
return None
或者使用其他
if userInputForQuestion not in self.questions[self.index].answers:
print("Try again.")
self.AskQuestion()
else:
self.questions[self.index].selectedAnswer = userInputForQuestion
self.index += 1;
还请注意,以这种方式使用递归并不常见。不管怎样,这都会让你犯错误。当询问产生异常的代码时,你应该始终在问题中包含完整的回溯。复制回溯并将其粘贴到问题中,然后将其格式化为代码(选择它并键入ctrl-k)为什么
QuestionAsker
是一个类?请展示您是如何使用它的-。