Python
Quiz model
Design the Question and Quiz class skeleton.
Project: Quiz app
In this five-lesson project you'll build a quiz app. Each lesson adds one piece, and by the final lesson you'll complete a working mini command-line application.
You'll use what you learned in previous groups: classes, dataclasses and lists. Throughout the project you'll design a Question class that holds the question text and the correct answer. You'll add a Quiz class to manage multiple questions. You'll also add play and scoring steps to finish the app.
Question skeleton
A question carries two core pieces of data: text and correct answer. With the @dataclass decorator you define this class in a short form: each field name gets a type and an empty-string default.
Example: @dataclass\nclass Question:\n text: str = ""\n answer: str = "". This definition auto-generates the constructor and comparison methods. To create a question you just write Question(text="Capital?", answer="Ankara").
Exercise Define the Question class
Start with from dataclasses import dataclass. Define a Question class with @dataclass; include fields text: str = "" and answer: str = "". Then create a question with q = Question(text="What is the capital?", answer="Ankara") and print its text with print(q.text).
Show example solution
# Define the Question dataclass and create one question
from dataclasses import dataclass
@dataclass
class Question:
text: str = ""
answer: str = ""
q = Question(text="What is the capital?", answer="Ankara")
print(q.text)
Test yourself
-
Why write the quiz with a dataclass?
- It defines question data and defaults in a short form
- It can be written without classes, no difference
- Dataclasses require a database
- A dataclass slows the program down
Show answer
It defines question data and defaults in a short form — A dataclass defines question data and defaults in a short form.
-
Complete the type of the Question field
@dataclass
class Question:
text: ____ = ""
answer: str = ""
Show answer
@dataclass
class Question:
text: str = ""
answer: str = ""
-
Match the quiz project concepts
- Question
- Holds question data
- text
- Question text
- answer
- Correct answer
- @dataclass
- Decorator
Next lesson: Adding questions