Python
Putting it together
Combine the Quiz class with a menu loop.
Bringing it together
All pieces are ready now: the Question class, the Quiz class, the add_question, play and check_answer methods, and the score attribute. Now we'll combine them into a working mini quiz app.
In the last step you'll create a three-question quiz, answer each one and print the score. We keep the answers hardcoded so the output stays deterministic; in a real app these might come from input(), but here we use fixed values for testability.
A three-question mini quiz
We'll define a quiz with three questions: "Capital?" (answer "Ankara"), "2x2?" (answer "4") and "Summer month?" (answer "June"). We add all three with add_question.
Then we give a guess to each with check_answer. Let the first two be correct and the third wrong. Expected score: 2. This clearly shows the app works.
Exercise Run the mini quiz app
All classes above are ready. Now create a quiz; add three questions: Question(text="Capital?", answer="Ankara"), Question(text="2x2?", answer="4") and Question(text="Summer month?", answer="June"). Show the questions with quiz.play(). Then call quiz.check_answer(quiz.questions[0], "Ankara"), quiz.check_answer(quiz.questions[1], "4") and quiz.check_answer(quiz.questions[2], "July"). Finally print the score with print(quiz.score).
Show example solution
from dataclasses import dataclass, field
@dataclass
class Question:
text: str = ""
answer: str = ""
@dataclass
class Quiz:
questions: list = field(default_factory=list)
score: int = 0
def add_question(self, q):
self.questions.append(q)
def play(self):
for i, q in enumerate(self.questions, start=1):
print(f"Question {i}: {q.text}")
def check_answer(self, q, guess):
if q.answer == guess:
self.score += 1
return True
return False
quiz = Quiz()
quiz.add_question(Question(text="Capital?", answer="Ankara"))
quiz.add_question(Question(text="2x2?", answer="4"))
quiz.add_question(Question(text="Summer month?", answer="June"))
quiz.play()
quiz.check_answer(quiz.questions[0], "Ankara")
quiz.check_answer(quiz.questions[1], "4")
quiz.check_answer(quiz.questions[2], "July")
print(quiz.score)
Test yourself
-
Why keep the answers hardcoded?
- The output is deterministic, testing is easier
- The program runs faster
- Classes use less memory
- The input() function fails
Show answer
The output is deterministic, testing is easier — With hardcoded answers the output is the same every run; testing is easier.
-
Complete the score print line
quiz.check_answer(quiz.questions[2], "Ankara")
print(quiz.____)
Show answer
quiz.check_answer(quiz.questions[2], "Ankara")
print(quiz.score)
-
Match the integration steps
- add_question
- Add a question
- play
- Show questions
- check_answer
- Check the answer
- quiz.score
- Print the score
Next lesson: ABC