类函数中递归调用引发IndexError问题排查
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:
- You call
AskQuestion()withindex = 0 - Input is invalid → you recursively call
AskQuestion()again (stillindex = 0) - Input is valid this time → the recursive call sets the selected answer, increments
indexto 1, and returns to the original call - The original call resumes execution, increments
indexagain to 2 - If you call
AskQuestion()again, it increments to 3, which is beyond yourquestionslist'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 +=1only runs once per valid answer, so you'll never accidentally jump past the end of yourquestionslist- It avoids the stack overflow risk that comes with deep recursion (unlikely here, but still a good practice)
If You Insist on Using Recursion (Not Recommended)
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

