Python
Running the quiz
Ask questions in turn with run.
Playing the quiz
You add a play method to the Quiz class to print every question to the screen. The method body loops over for q in self.questions: and shows the text with print(q.text).
This simple play lists the questions without waiting for input. Later we'll add answer comparison with check_answer. For now the goal is to show questions in order; scoring comes in the next lesson.
Showing questions in order
During play you may also want to show the order of each question. Using enumerate(self.questions, start=1) gives you both the index and the question. So the output looks like Question 1: ..., Question 2: ....
You format with an f-string: f"Question {i}: {q.text}". Here i is the index, q.text is the question text. This makes the output testable and deterministic; each run gives the same result.
Exercise Add the play method
Add a method def play(self): to the Quiz class above. Its body should have for i, q in enumerate(self.questions, start=1): and print(f"Question {i}: {q.text}"). Then create a quiz, add two questions (text="Capital?" and text="2x2?") and call quiz.play().
Show example solution
from dataclasses import dataclass, field
@dataclass
class Question:
text: str = ""
answer: str = ""
@dataclass
class Quiz:
questions: list = field(default_factory=list)
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}")
quiz = Quiz()
quiz.add_question(Question(text="Capital?", answer="Ankara"))
quiz.add_question(Question(text="2x2?", answer="4"))
quiz.play()
Test yourself
-
What does the play method return?
- Only prints text, returns nothing
- The correct answers
- A list
- The total score
Show answer
Only prints text, returns nothing — The play method uses print.
-
Match the play parts
- for q in self.questions
- Loop
- enumerate(...)
- Index
- print(q.text)
- Print text
- f"Question {i}: ..."
- Formatted output
-
Complete the play method body
def play(self):
for i, q in enumerate(self.questions, start=1):
print(f"Question {____}: {q.text}")
Show answer
def play(self):
for i, q in enumerate(self.questions, start=1):
print(f"Question {i}: {q.text}")
Next lesson: Score calculation