You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类函数中递归调用引发IndexError问题排查

Fixing IndexError in QuestionAsker's AskQuestion Method

Let's break down why you're hitting that IndexError and fix it right away.

The Root Cause

Your issue comes from using recursion to handle invalid input. Here's what's happening step-by-step when you enter multiple wrong answers then a correct one:

  1. You call AskQuestion() with index = 0
  2. Input is invalid → you recursively call AskQuestion() again (still index = 0)
  3. Input is valid this time → the recursive call sets the selected answer, increments index to 1, and returns to the original call
  4. The original call resumes execution, increments index again to 2
  5. If you call AskQuestion() again, it increments to 3, which is beyond your questions list's bounds (indices 0-2) → boom, IndexError

Every recursive layer runs the self.index +=1 line, leading to over-incrementing.

The Fix: Use a Loop Instead of Recursion

Recursion is overkill here—loops are far more reliable for repeated input validation. Replace your AskQuestion() method with this:

def AskQuestion(self):
    # Loop until we get a valid answer
    while True:
        userInputForQuestion = raw_input(self.questions[self.index].question + " ")
        if userInputForQuestion in self.questions[self.index].answers:
            self.questions[self.index].selectedAnswer = userInputForQuestion
            self.index += 1
            break  # Exit loop once valid input is received
        print("Try again.")

Why This Works

  • The loop keeps asking for input until the user enters a valid option
  • self.index +=1 only runs once per valid answer, so you'll never accidentally jump past the end of your questions list
  • It avoids the stack overflow risk that comes with deep recursion (unlikely here, but still a good practice)

If you want to keep the recursive pattern for some reason, add a return statement right after the recursive call to prevent the original layer from incrementing the index again:

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()
        return  # Stop execution here so we don't increment index twice
    self.questions[self.index].selectedAnswer = userInputForQuestion
    self.index += 1

But again, the loop approach is cleaner and more maintainable for this use case.

内容的提问来源于stack exchange,提问作者Michael Brennan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:19:39