0%

Your First Classes and Objects · capstone

Capstone project: Project: Replace Quiz Dictionaries with Objects

This chapter began with question that could accidentally use the wrong keys. Step by step, you defined a Question class, created initialized instances, moved answer checking into a , and let a Quiz work with a collection of questions.

The project now combines that sequence into one working quiz model. You will build:

  • a Question class that creates dependable question ;

  • an is_correct method that owns the answer-matching rule;

  • a Quiz class that contains questions;

  • a check_answer method that delegates to one question;

  • a score method that checks a sequence of responses.

What the classes must support

Other code should be able to create questions, build a quiz, check one answer, and calculate a score:

questions = [
    Question("Two plus two?", "4"),
    Question("Three plus three?", "6"),
]
quiz = Quiz(questions)

assert quiz.check_answer(0, "4")
assert quiz.score(["4", "5"]) == 1

You may add helpful or methods. Keep the shown constructor and method names working so the example and hidden checks can use the classes in the same way.

Build in small steps

  1. Finish Question.__init__.

  2. Finish Question.is_correct.

  3. Finish Quiz.__init__.

  4. Finish Quiz.check_answer.

  5. Finish Quiz.score.

  6. Run the program and submit it.

Quiz.score receives one response for each question. It should return the number of correct responses.

One clear approach is to start a counter at zero, over matching question and response positions, and add one when check_answer returns True.

Review the design

After the project passes, compare it with the dictionary version:

  • What shape can no longer be created accidentally through the normal constructor?

  • Which object owns answer checking?

  • What became easier to read?

  • What extra structure did the classes introduce?

Classes are valuable when their clearer promises justify that structure. This project gives you a concrete design to evaluate rather than a rule that classes are always better.

Which responsibility belongs most naturally to Question?

Task

Complete the two classes so the final program prints:

Score: 2/3

Submit when your Question keep independent state, Quiz delegates answer checking, and score works for both the provided data and other questions.