Python 中的简单测验,它以“answer,question”格式读取 csv 文件。在我决定尝试重构我的原始代码之前,该程序正在运行。我参考了不同的来源来确定 csv、random、classes 和 loop 是否正确编码,但代码不能使用这个更新的重构版本运行。
原始代码
player_name = input("What is your name? ")
print(f"Welcome, {player_name}, to Quiz!")
play_quiz = str(input("Are you ready to play?\n"))
if play_quiz != "y":
exit()
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
# sample quiz questions go here where ["Question", "Answer choices from a-c"]
question_prompts = []
questions = [
Question(question_prompts[0], "b"),
Question(question_prompts[1], "a"),
]
def run_test(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
print("You answered " + str(score) + "/" + str(len(questions)) + " correct.")
return input("Want to play again? (y/n): ") == "y".lower()
play_again = True
while play_again:
play_again = run_test(questions)
重构代码
import csv
import random
player_name = input("What is your name? ")
print(f"Welcome, {player_name}, to the Quiz!")
play_quiz = str(input("Are you ready to play? "))
if play_quiz != "y":
exit()
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
def quiz():
score = 0
questions_right = 0
quiz_file = open(characters_file, "r")
quiz_data = quiz_file.readlines()
random.shuffle(quiz_data)
question_number = 1
for question in range(65):
x = quiz_data[question].strip()
data = x.split(",")
Question = data.prompt[1]
correct_answer = data.answer[1]
def run_test(quiz_data):
answer = input("What is your answer? ")
if answer == correct_answer:
score += 1
question_right = question_number + 1
else:
print("Incorrect.")
print(f"Correct answer should be: {CorrectAnswer}")
我不明白我做错了什么,因为它没有使用下面的重构代码运行。本质上,我做错了什么?我是否将代码放在错误的位置以使其无法运行?
杨魅力
相关分类