首页 > 解决方案 > 递归调用导致类函数中的 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!

我在这里束手无策,我在这方面看到的其他问题并没有太大帮助。希望各位大神帮忙,谢谢!

标签: pythonclassooprecursion

解决方案


请注意,在您的函数体中,当给出错误答案时,函数不会结束。它进行递归调用。当该调用结束时,索引仍会递增。所以错误的答案仍然会弄乱索引。

您应该在进行错误调用后结束该函数,以实现您想要发生的事情。

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;

另请注意,以这种方式使用递归并不常见。无论如何,这使您犯了错误。


推荐阅读