Python 中的测验 - 原始程序已运行,但已重构且现在无法运行

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}")


我不明白我做错了什么,因为它没有使用下面的重构代码运行。本质上,我做错了什么?我是否将代码放在错误的位置以使其无法运行?


九州编程
浏览 218回答 1
1回答

杨魅力

我认为您错误地使用了Question您制作的课程。你试图做Question = data.prompt[1]这并没有真正意义。Question 是一个类,因此您将使用它来创建对象的实例。此外,您的班级期望值prompt并answer传递给它。按照您现在的设置方式,您可以按照new_question = Question("What color is the sky?", "blue"). 但是,我认为在此代码中创建类没有多大用处,因为您没有附加任何方法......下面是一个测验类思想的例子,可以帮助你掌握 OOP 编程的概念:import randomquestions = [    "What color is the sky?",    "What year is it?"]answers = [    "blue",    "2019"]class Question:    def __init__(self):        index = random.randint(0, len(questions) - 1)        self.answer = answers[index]        self.question = questions[index]    def check_valid(self, guess):        if guess == self.answer:            return True        else:            return Falseif __name__ == "__main__":    name = str(input("What's your name?\n"))    print('Welcome then {} welcome to the quiz!'.format(name))    while True:        new_question = Question()        check = False        while check is not True:            print(new_question.question)            user_guess = str(input('What do you think the answer is?\n'))            check = new_question.check_valid(user_guess)  您可以看到,在该__init__(self):部分中,代码并未真正进行任何主要计算,而只是设置了以后可以调用的内容,例如new_question.question. 但是,您可以连接方法,像类check_valid(由压痕连接到类def),再后来就用在这些方法的实例创建类的。我的代码中没有很多函数(例如退出循环的能力),但希望这能帮助您更深入地理解 OOP!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python