Python Project Text Quiz
What you will build
- A multiple-choice quiz whose questions live in a JSON file
- Loading with validation, shuffling, scoring and grading
- A results file with a top-three ranking
- Tests with scripted answers and a seeded random generator
1. The idea
The quiz asks each question once, in random order, accepts the answer as a letter, says whether it was right, and shows a score and a list of questions to review at the end. The questions are data, not code: anyone can write a new quiz by editing a JSON file, with no Python needed. That is a very common pattern: keep content in data files, keep logic in code.
2. The data format
[
{"question": "Which function shows text on the screen?",
"choices": ["print", "show", "echo", "write"],
"answer": "print"},
{"question": "What does len([4, 5, 6]) return?",
"choices": ["2", "3", "4", "6"],
"answer": "3"}
]
Each item has the question, a list of 2 to 4 choices, and the text of the correct choice. Storing the answer as text (not "the second one") means shuffling or editing the choices cannot silently break it.
3. The design
| Piece | Job |
|---|---|
Question (frozen dataclass) |
text, choices (a tuple), answer (index of the correct choice) |
load_questions(path) |
read the JSON and check every question; errors name the question number |
read_choice(text, count) |
turn a, B, c into an index, or raise ValueError |
run_quiz(questions, ask, show, rng) |
ask everything in random order; return the score and the questions missed |
grade(score, total) |
percentage and a label |
save_result(path, name, score, total) |
add to a results file and return the best three |
As in the earlier projects, run_quiz takes ask and show functions instead of using input and print, and takes the random generator rng as a parameter, so tests can control both.
4. The code
quiz.py:
"""A text quiz: questions come from a JSON file, results are scored and saved."""
import json
import random
from dataclasses import dataclass
from pathlib import Path
LETTERS = "abcd"
@dataclass(frozen=True)
class Question:
text: str
choices: tuple
answer: int # index of the correct choice
def load_questions(path):
"""Read questions from JSON, checking every one carefully."""
data = json.loads(Path(path).read_text(encoding="utf-8"))
questions = []
for number, item in enumerate(data, start=1):
try:
choices = tuple(item["choices"])
if not 2 <= len(choices) <= len(LETTERS):
raise ValueError("2 to 4 choices are needed")
if len(set(choices)) != len(choices):
raise ValueError("choices must be different")
if item["answer"] not in choices:
raise ValueError("the answer must be one of the choices")
questions.append(Question(item["question"], choices, choices.index(item["answer"])))
except KeyError as error:
raise ValueError(f"question {number}: missing {error.args[0]!r}") from None
except ValueError as error:
raise ValueError(f"question {number}: {error}") from None
return questions
def read_choice(text, count):
"""Return the chosen index from a letter such as 'a' or 'B'; raise ValueError if invalid."""
text = text.strip().lower()
if len(text) == 1 and text in LETTERS[:count]:
return LETTERS.index(text)
raise ValueError(f"type a letter from a to {LETTERS[count - 1]}")
def run_quiz(questions, ask, show, rng=None):
"""Ask every question once, in random order. Returns (score, wrong answers)."""
rng = rng or random.Random()
order = rng.sample(questions, len(questions))
score, missed = 0, []
for number, q in enumerate(order, start=1):
show(f"Question {number} of {len(order)}: {q.text}")
for letter, choice in zip(LETTERS, q.choices):
show(f" {letter}) {choice}")
while True:
try:
picked = read_choice(ask("Your answer: "), len(q.choices))
break
except ValueError as error:
show(f" {error}")
if picked == q.answer:
score += 1
show(" Correct!")
else:
show(f" No. The answer is {LETTERS[q.answer]}) {q.choices[q.answer]}.")
missed.append(q.text)
return score, missed
def grade(score, total):
percent = round(100 * score / total) if total else 0
if percent >= 90:
label = "excellent"
elif percent >= 70:
label = "good"
elif percent >= 50:
label = "keep practising"
else:
label = "try again"
return percent, label
def save_result(path, name, score, total):
"""Append the result to a JSON file and return the best three so far."""
path = Path(path)
results = json.loads(path.read_text(encoding="utf-8")) if path.exists() else []
results.append({"name": name, "score": score, "total": total})
path.write_text(json.dumps(results, indent=2), encoding="utf-8")
ranked = sorted(results, key=lambda r: r["score"] / r["total"], reverse=True)
return ranked[:3]
How it works:
load_questionsturns each JSON object into aQuestionand rejects bad ones withquestion N: message. The twoexceptclauses turn missing keys and our own checks into one error type. (A first version let Python's owntuple.index(x): x not in tuplemessage through; the explicitintest gives a message a quiz author understands.)rng.sample(questions, len(questions))returns a shuffled copy and leaves the original list alone (lesson 17.2).zip(LETTERS, q.choices)pairs each choice with its letter (lesson 6.6).- The inner
while Trueloop asks again after a bad entry, withbreakonce a valid letter has been read (lesson 6.3). read_choicerequires a single character inabcd[:count]. An early idea was to accept digits too, but a choice such as3would then be ambiguous (the number 3 or option 3?). Simple rules beat clever ones.gradeguards against dividing by zero when there are no questions (if total).save_resultappends and returns the three best results, sorted by the fraction correct (score / total), so quizzes of different lengths compare fairly (lesson 9.6).
Quick check: why does `run_quiz` receive `rng` as a parameter?
So a test can pass a seeded generator and get the same question order every time.
5. A scripted run
This demo loads four questions from a temporary JSON file, shuffles them with the seed 5, and answers with a prepared list (including one invalid entry, x, and one wrong answer):
score, missed = run_quiz(questions, scripted(["c", "x", "B", "a", "a"]), print, random.Random(5))
percent, label = grade(score, len(questions))
print(f"Score: {score}/{len(questions)} = {percent}% ({label})")
print("To review:", missed)
Output:
4 questions loaded
Question 1 of 4: Which type holds True or False?
a) int
b) str
c) bool
Your answer: c
Correct!
Question 2 of 4: What is 7 // 2?
a) 3.5
b) 3
c) 4
d) 2
Your answer: x
type a letter from a to d
Your answer: B
Correct!
Question 3 of 4: What does len([4, 5, 6]) return?
a) 2
b) 3
c) 4
d) 6
Your answer: a
No. The answer is b) 3.
Question 4 of 4: Which function shows text on the screen?
a) print
b) show
c) echo
d) write
Your answer: a
Correct!
Score: 3/4 = 75% (good)
To review: ['What does len([4, 5, 6]) return?']
best three: [('Sam', 4), ('Rina', 3), ('Lee', 1)]
bad question file: question 1: the answer must be one of the choices
(The Your answer: lines show what the scripted player typed. The "best three" line comes from saving three results, Rina 3 of 4, Sam 4 of 4 and Lee 1 of 4, and the last line from a deliberately broken question file.) The invalid x produced a hint and did not count as an answer; the capital B was accepted.
6. Tests
test_quiz.py uses the same trick as before. To answer correctly without knowing the shuffled order, the test builds the same order with an identical seed:
import json
import random
import tempfile
import unittest
from pathlib import Path
from quiz import Question, grade, load_questions, read_choice, run_quiz, save_result
Q1 = Question("Two plus two?", ("3", "4"), 1)
Q2 = Question("Capital letter?", ("a", "A", "1"), 1)
def scripted(answers):
items = iter(answers)
return lambda prompt: next(items)
class TestChoice(unittest.TestCase):
def test_letters_any_case_and_spaces(self):
self.assertEqual(read_choice(" B ", 4), 1)
self.assertEqual(read_choice("a", 2), 0)
def test_rejects_out_of_range_and_other_text(self):
for bad in ["", "e", "c", "ab", "1", "bool"]:
with self.subTest(bad=bad):
with self.assertRaises(ValueError):
read_choice(bad, 2)
class TestRun(unittest.TestCase):
def test_score_and_missed(self):
rng = random.Random(1)
order = random.Random(1).sample([Q1, Q2], 2) # the same order the quiz will use
answers = ["abc"[q.answer] for q in order]
score, missed = run_quiz([Q1, Q2], scripted(answers), lambda m: None, rng)
self.assertEqual((score, missed), (2, []))
def test_wrong_and_invalid_answers(self):
shown = []
order = random.Random(1).sample([Q1, Q2], 2)
wrong = ["a" if q.answer != 0 else "b" for q in order]
score, missed = run_quiz([Q1, Q2], scripted(["?"] + wrong), shown.append, random.Random(1))
self.assertEqual(score, 0)
self.assertEqual(len(missed), 2)
self.assertTrue(any("type a letter" in m for m in shown))
class TestGrade(unittest.TestCase):
def test_labels(self):
self.assertEqual(grade(9, 10), (90, "excellent"))
self.assertEqual(grade(7, 10), (70, "good"))
self.assertEqual(grade(5, 10), (50, "keep practising"))
self.assertEqual(grade(4, 10), (40, "try again"))
self.assertEqual(grade(0, 0), (0, "try again"))
class TestFiles(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.dir = Path(self.folder.name)
def tearDown(self):
self.folder.cleanup()
def test_load_valid_and_invalid(self):
good = [{"question": "q", "choices": ["x", "y"], "answer": "y"}]
(self.dir / "q.json").write_text(json.dumps(good), encoding="utf-8")
self.assertEqual(load_questions(self.dir / "q.json")[0].answer, 1)
for bad in ([{"question": "q", "choices": ["x", "x"], "answer": "x"}],
[{"question": "q", "choices": ["x"], "answer": "x"}],
[{"question": "q", "choices": ["x", "y"], "answer": "z"}],
[{"choices": ["x", "y"], "answer": "x"}]):
(self.dir / "q.json").write_text(json.dumps(bad), encoding="utf-8")
with self.assertRaises(ValueError):
load_questions(self.dir / "q.json")
def test_results_ranked(self):
path = self.dir / "r.json"
save_result(path, "a", 1, 4)
save_result(path, "b", 4, 4)
best = save_result(path, "c", 2, 4)
self.assertEqual([r["name"] for r in best], ["b", "c", "a"])
if __name__ == "__main__":
unittest.main()
Result: Ran 7 tests ... OK. To play with your own questions, save them as questions.json, and write a short main that calls load_questions, run_quiz(questions, input, print), grade and save_result.
7. Ideas to extend it
- A
mainwithargparse(lesson 17.8):python quiz.py questions.json --count 10 --name Rina. - Random subset: ask only
nquestions (rng.sample(questions, n)). - Categories and difficulty fields, with a filter.
- Timer: record the time per question with
time.perf_counter()and add it to the result. - Explanations: an optional
explainfield shown after a wrong answer. - Shuffle the choices too (remember to track which one is correct).
- A review mode that repeats only the missed questions.
- Different question types: true/false, typed answers (compare after
strip().lower()).
Worked example: what makes this program easy to change
| Change you want | Where to make it |
|---|---|
| a new quiz | edit or add a JSON file; no code changes |
| a new grading scale | grade only |
| show messages in a window instead of the terminal | pass a different show and ask to run_quiz |
| 5-choice questions | change LETTERS; the loops use zip(LETTERS, ...) and len(q.choices) |
| more checks on question files | load_questions only |
| store results in a database | save_result only (lesson 17.10) |
The reasons: the data is outside the code, every function has one job, and side effects (input, output, files, randomness) are passed in or kept at the edges. These are the habits that let a program grow without turning into a tangle. The quiz questions here are simple Python facts written for the lesson.
Common mistakes
- Hard-coding the questions in the program.
- Trusting the question file without validation.
- Storing the correct answer as a position that breaks when choices are reordered.
- Using
random.shuffleon the original list and changing it for everyone (usesamplefor a copy). - Not handling invalid input (an empty line,
e, a number). - Dividing by zero when there are no questions.
- Comparing scores of different-length quizzes by raw numbers instead of percentages.
- Overwriting the results file instead of appending.
Key takeaways
- Keep content (questions) in a data file and logic in code; validate data when loading and report which item is wrong.
- Pass input, output and the random generator into the functions, so tests can script them.
random.samplegives a shuffled copy; store the answer by value so shuffling is safe.- Keep input rules simple and unambiguous.
- Compare results as fractions, and test file handling with temporary directories.
Practice
1. Why is the correct answer stored as the choice text in the JSON file?
Show answer
It stays correct if choices are reordered or edited, and it is easier for question writers to read than a position number.
2. What does rng.sample(questions, len(questions)) do?
Show answer
Returns a new list with all the questions in random order, leaving questions unchanged.
3. How would you ask only 10 random questions?
Show answer
Use rng.sample(questions, min(10, len(questions))) in run_quiz (or pass a smaller list).
4. Why does grade check if total?
Show answer
With no questions, score / total would divide by zero.
5. Add true/false questions. What must change?
Show answer
Nothing in the logic: write them as two-choice questions ["True", "False"]. The loader already allows 2 to 4 choices.
6. How could the program sort the best results fairly across quizzes of different length?
Show answer
By the fraction score / total, as save_result does, instead of the raw score.