Quiz model
- Python course
- Intermediate
- Lesson 42/116
- 6 min
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").
Practice 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).
Starter code
# Define the Question dataclass and create one questionSample 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)Expected output
What is the capital?
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why write the quiz with a dataclass?
- It defines question data and defaults in a short form Correct answer
- It can be written without classes, no difference
- Dataclasses require a database
- A dataclass slows the program down
Explanation: A dataclass defines question data and defaults in a short form.
2 Complete the type of the Question field
@dataclass
class Question:
text: ____ = ""
answer: str = ""
@dataclass
class Question:
text: str = ""
answer: str = ""
Explanation: The text field is text, so the type is str.
3 Match the quiz project concepts
| Term | Meaning |
|---|---|
Question |
Holds question data |
text |
Question text |
answer |
Correct answer |
@dataclass |
Decorator |