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

时间:2019-02-08 23:36:58

标签: python csv oop random import

Python中的简单测验,可读取“答案,问题”格式的csv文件。在我决定尝试重构原始代码之前,该程序已运行。我引用了不同的来源来确定csv,random,类和循环是否正确编码,但是该代码无法与此更新的重构版本一起运行。

原始代码

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

    total_score = (score / 65) * 100 
    print("You answered " + str(score) + "/" + str(total_score) + " question correct.")
    print("You have a score of " + str(total_score) + "%")

    return input("Want to play again? (y/n): ") == "y".lower()

 quiz()
 quiz_file.close()
 play_again = True
 while play_again:
     play_again = run_test()

我看不到我在做什么错,因为它不能与下面的重构代码一起运行。本质上,我在做什么错?我是否将代码放在错误的位置以使其无法运行?

1 个答案:

答案 0 :(得分:1)

我认为您错误地使用了自己制作的Question类。您尝试做Question = data.prompt[1],这实际上没有任何意义。 Question是一个类,因此您可以使用它来创建对象的 instances 。此外,您的班级希望将值promptanswer传递给它。现在,您可以按照new_question = Question("What color is the sky?", "blue")的方式进行设置。但是,我发现在此代码中创建类没有太大用处,因为您没有附加任何方法...

这是一个测验类概念的示例,可以帮助您掌握OOP编程的概念:

import random

questions = [
    "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 False

if __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附加到类),然后在 instances < / em>创建的类。我的代码中没有很多功能(例如退出循环的功能),但希望这可以帮助您更深入地了解OOP!