Python CSV读取测验代码重构后无法运行问题排查
Hey there! Let's break down all the issues in your refactored code step by step—there are quite a few structural and logical mistakes that are keeping it from running properly:
1. Undefined Variables & Scope Issues
characters_fileis never defined before you try to open it withopen(characters_file, "r")—you need to specify the actual file path/name here, like"quiz_questions.csv".CorrectAnswer(capitalized) is referenced in your error message, but you defined the variable ascorrect_answer(lowercase)—this will throw aNameError.quiz_fileis created inside thequiz()function, so trying to callquiz_file.close()outside the function will fail (it's out of scope). You should use awithstatement to handle file opening/closing automatically instead.
2. Misuse of the Question Class & Data Handling
- You're overwriting the
Questionclass with a variable:Question = data.prompt[1]—this is a critical mistake. First,datais a list from splitting a CSV line, so it doesn't have apromptattribute. You should create instances of yourQuestionclass properly (e.g.,Question(data[1], data[0])since your CSV uses theanswer,questionformat). - Using
split(",")to parse CSV is unreliable—if your answers or questions contain commas, this will break. You should use thecsv.readerclass from thecsvmodule instead, which handles proper CSV parsing.
3. Nested Function & Scope Problems
- You defined
run_test()inside thequiz()function's for loop—this meansrun_testis only accessible inside that loop, and it gets redefined every iteration. Your outerwhile play_againloop tries to callrun_test()which doesn't exist in that scope, causing aNameError. - Variables like
score,correct_answer, andquestion_numberare in the outerquiz()scope, but modifyingscoreinsiderun_test()will cause anUnboundLocalErrorunless you declare it asnonlocal.
4. Logical & Loop Errors
for question in range(65)assumes your CSV has exactly 65 questions—if it has fewer, you'll get anIndexErrorwhen accessingquiz_data[question]. You should loop over the shuffled data directly instead of hardcoding 65.- Your score calculation is inside the loop, so it prints the total score after every single question instead of at the end of the quiz.
- The output string
print("You answered " + str(score) + "/" + str(total_score) + " question correct.")is broken—total_scoreis a percentage, not the number of questions. It should reference the total number of questions instead. question_right = question_number + 1has a typo (should bequestions_right), and the logic doesn't make sense here—you probably want to incrementquestions_rightwhen the answer is correct, not set it toquestion_number + 1.
5. Play Again Logic Breakage
- The
play_againloop is outside thequiz()function, butrun_test()doesn't exist there, and even if it did, your current setup doesn't properly reset the quiz state for a new playthrough.
Fixed Refactored Code Example
Here's a corrected version that fixes all these issues, uses proper CSV handling, and maintains the play-again functionality:
import csv import random class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer def load_questions(file_path): questions = [] # Use with statement to auto-close the file safely with open(file_path, "r") as quiz_file: csv_reader = csv.reader(quiz_file) # CSV format is "answer,question" so row[0] = answer, row[1] = prompt for row in csv_reader: questions.append(Question(row[1], row[0])) return questions def run_test(questions): score = 0 # Shuffle questions without modifying the original list shuffled_questions = random.sample(questions, len(questions)) for idx, question in enumerate(shuffled_questions, 1): print(f"\nQuestion {idx}: {question.prompt}") answer = input("Your answer: ").strip().lower() if answer == question.answer.lower(): print("Correct!") score += 1 else: print(f"Incorrect. The correct answer is: {question.answer}") total_questions = len(shuffled_questions) percentage_score = (score / total_questions) * 100 if total_questions > 0 else 0 print(f"\n--- Quiz Complete ---") print(f"You answered {score}/{total_questions} questions correctly.") print(f"Your score: {percentage_score:.1f}%") return input("\nWant to play again? (y/n): ").strip().lower() == "y" def main(): player_name = input("What is your name? ") print(f"Welcome, {player_name}, to the Quiz!") play_quiz = input("Are you ready to play? (y/n): ").strip().lower() if play_quiz != "y": return # Replace with your actual CSV file path questions = load_questions("quiz_questions.csv") if not questions: print("No questions found in the CSV file.") return play_again = True while play_again: play_again = run_test(questions) if __name__ == "__main__": main()
Key Improvements in the Fixed Code:
- Separated concerns:
load_questionshandles CSV reading,run_testmanages quiz flow,mainhandles setup and play-again logic. - Uses
csv.readerfor reliable CSV parsing (handles commas in questions/answers). - Uses
withstatement to avoid file leaks. - Shuffles questions without altering the original list.
- Proper scope management for all variables.
- Clearer user prompts and formatted output.
- Handles edge cases like empty CSV files.
内容的提问来源于stack exchange,提问作者user11036037
相关产品推荐
相关产品推荐

