Exam System

Define a class Exam with private attributes for questions and answers. Implement a method to quiz the user, recording their answers privately, and provide a method to grade the exam.

Example 1:

Input: Questions: ["What is 2+2?", "What is the capital of France?"], Answers: [4, "Paris"], User Answers: [4, "Paris"] 
Output: 100%

Example 2:

Input: Questions: ["What is 2+2?", "What is the capital of France?"], Answers: [4, "Paris"], User Answers: [5, "London"]
Output: 0%

Maintain private attributes for questions, correct answers, and user answers. Implement methods to ask questions, store user responses, and then compare them with correct answers to grade the exam.

class Exam:
    def __init__(self, questions, answers):
        self._questions = questions
        self._answers = answers
        self._user_answers = []

    def quiz(self, user_answers):
        self._user_answers = user_answers

    def grade(self):
        correct_answers = sum(1 for a, b in zip(self._answers, self._user_answers) if a == b)
        return (correct_answers / len(self._answers)) * 100

# Test the class
questions = ["What is 2+2?", "What is the capital of France?"]
answers = [4, "Paris"]

exam = Exam(questions, answers)
exam.quiz([4, "Paris"])
print(exam.grade())  # Output: 100.0

exam.quiz([5, "London"])
print(exam.grade())  # Output: 0.0

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!