Quiz Brain

The QuizBrain, as the name suggests, is the brain of the application. Let's create quiz_brain.py file and add the following code there:

class QuizBrain:

    def __init__(self, questions):
        self.question_no = 0
        self.score = 0
        self.questions = questions
        self.current_question = None

    def has_more_questions(self):
        """To check if the quiz has more questions"""
        
        return self.question_no < len(self.questions)

    def next_question(self):
        """Get the next question by incrementing the question number"""
        
        self.current_question = self.questions[self.question_no]
        self.question_no += 1
        q_text = self.current_question.question_text
        return f"Q.{self.question_no}: {q_text}"

    def check_answer(self, user_answer):
        """Check the user answer against the correct answer and maintain the score"""
        
        correct_answer = self.current_question.correct_answer
        if user_answer.lower() == correct_answer.lower():
            self.score += 1
            return True
        else:
            return False

    def get_score(self):
        """Get the number of correct answers, wrong answers and score percentage."""
        
        wrong = self.question_no - self.score
        score_percent = int(self.score / self.question_no * 100)
        return (self.score, wrong, score_percent)
The QuizBrain class takes questions, list of questions. Additionally, the question_no and score attributes are initialized with 0 and the current_question is set to None initially.

The first method has_more_questions() checks whether the quiz has more questions or not. The next method next_question() gets the question from the questions list at index question_no and then increments the question_no attribute returns a formatted question. The check_answer() method takes user_answer as an argument and checks whether the user's answer is correct or not. It also maintains the score and returns boolean values. The last method get_score() returns the number of correct answerswrong answers, and score percentage.

Discussion

3

0