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

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_file is never defined before you try to open it with open(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 as correct_answer (lowercase)—this will throw a NameError.
  • quiz_file is created inside the quiz() function, so trying to call quiz_file.close() outside the function will fail (it's out of scope). You should use a with statement to handle file opening/closing automatically instead.

2. Misuse of the Question Class & Data Handling

  • You're overwriting the Question class with a variable: Question = data.prompt[1]—this is a critical mistake. First, data is a list from splitting a CSV line, so it doesn't have a prompt attribute. You should create instances of your Question class properly (e.g., Question(data[1], data[0]) since your CSV uses the answer,question format).
  • Using split(",") to parse CSV is unreliable—if your answers or questions contain commas, this will break. You should use the csv.reader class from the csv module instead, which handles proper CSV parsing.

3. Nested Function & Scope Problems

  • You defined run_test() inside the quiz() function's for loop—this means run_test is only accessible inside that loop, and it gets redefined every iteration. Your outer while play_again loop tries to call run_test() which doesn't exist in that scope, causing a NameError.
  • Variables like score, correct_answer, and question_number are in the outer quiz() scope, but modifying score inside run_test() will cause an UnboundLocalError unless you declare it as nonlocal.

4. Logical & Loop Errors

  • for question in range(65) assumes your CSV has exactly 65 questions—if it has fewer, you'll get an IndexError when accessing quiz_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_score is a percentage, not the number of questions. It should reference the total number of questions instead.
  • question_right = question_number + 1 has a typo (should be questions_right), and the logic doesn't make sense here—you probably want to increment questions_right when the answer is correct, not set it to question_number + 1.

5. Play Again Logic Breakage

  • The play_again loop is outside the quiz() function, but run_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_questions handles CSV reading, run_test manages quiz flow, main handles setup and play-again logic.
  • Uses csv.reader for reliable CSV parsing (handles commas in questions/answers).
  • Uses with statement 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:32:52