CodeBlanks Logo Icon CodeBlanks

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.

Practice 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().

Starter code

main.py
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)

# Add a play method to the Quiz class

# Create a quiz, add two questions and call play

Sample solution

main.py
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()

Expected output

Question 1: Capital?
Question 2: 2x2?

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the play method return?

  • Only prints text, returns nothing Correct answer
  • The correct answers
  • A list
  • The total score

Explanation: The play method uses print.

2 Match the play parts

Term Meaning
for q in self.questions Loop
enumerate(...) Index
print(q.text) Print text
f"Question {i}: ..." Formatted output

3 Complete the play method body

Question
    def play(self):
        for i, q in enumerate(self.questions, start=1):
            print(f"Question {____}: {q.text}")
Answer
    def play(self):
        for i, q in enumerate(self.questions, start=1):
            print(f"Question {i}: {q.text}")

Explanation: The index is in the i variable.

All lessons in Intermediate