Project: Quiz Game
In this project you'll build a multiple-choice quiz game for the terminal. It shuffles the questions and answers, checks the player's replies, keeps score, gives feedback and lists the questions to review, all in about 100 lines of Python.
The goal
Quizzes are a great way to revise for exams, and building one teaches you how to structure data and logic cleanly. Our game will:
- store questions as a list of dictionaries, so adding new questions needs no code changes;
- shuffle the question order and the order of options every round;
- accept answers A to D in either case, rejecting anything else politely;
- show the score as a fraction and a percentage, with a message to match;
- list missed questions with their correct answers, and offer to play again while tracking the best score.
You'll use lists, dictionaries, while loops, return values and the random module from the standard library.
Step 1: Store the questions as data
Each question is a dictionary with the question text, a list of four options and the correct answer. Keeping the correct answer as text (not a letter) is important, because we'll shuffle the options and the letters will change.
Step 2: Ask one question
ask_question() copies and shuffles the options, prints them with letters, loops until the reply is a single letter from A to D, then checks it. It returns True or False, so the caller can keep score. zip(LETTERS, options) pairs each letter with an option, and LETTERS.index(reply) turns a letter back into a position.
Step 3: The full program
Save this as quiz_game.py:
"""Kuza Quiz: a multiple-choice quiz game with scoring."""
import random
QUESTIONS = [
{
"question": "What is the capital city of Uganda?",
"options": ["Kampala", "Entebbe", "Jinja", "Gulu"],
"answer": "Kampala",
},
{
"question": "Which keyword defines a function in Python?",
"options": ["func", "def", "function", "lambda"],
"answer": "def",
},
{
"question": "What does len('Kuza') return?",
"options": ["3", "4", "5", "An error"],
"answer": "4",
},
{
"question": "Which lake is the largest in Africa?",
"options": ["Lake Tanganyika", "Lake Turkana", "Lake Victoria", "Lake Malawi"],
"answer": "Lake Victoria",
},
{
"question": "What is 7 // 2 in Python?",
"options": ["3.5", "3", "4", "1"],
"answer": "3",
},
]
LETTERS = "ABCD"
def ask_question(number, item):
"""Ask one question. Return True if the player answers correctly."""
options = item["options"][:] # copy, so shuffling doesn't change QUESTIONS
random.shuffle(options)
print(f"\nQuestion {number}: {item['question']}")
for letter, option in zip(LETTERS, options):
print(f" {letter}) {option}")
while True:
reply = input("Your answer (A-D): ").strip().upper()
if len(reply) == 1 and reply in LETTERS:
break
print("Please type A, B, C or D.")
chosen = options[LETTERS.index(reply)]
if chosen == item["answer"]:
print("Correct!")
return True
print(f"Not quite. The answer is {item['answer']}.")
return False
def grade_message(percent):
if percent == 100:
return "Perfect score! Hongera!"
if percent >= 70:
return "Great work!"
if percent >= 40:
return "Good effort. Review the questions you missed."
return "Keep practising. You'll get there!"
def play_round(name):
questions = random.sample(QUESTIONS, len(QUESTIONS)) # shuffled copy
score = 0
missed = []
for number, item in enumerate(questions, start=1):
if ask_question(number, item):
score += 1
else:
missed.append(item)
percent = score / len(questions) * 100
print(f"\n{name}, you scored {score}/{len(questions)} ({percent:.0f}%).")
print(grade_message(percent))
if missed:
print("Questions to review:")
for item in missed:
print(f" - {item['question']} (Answer: {item['answer']})")
return score
def main():
print("=== Kuza Ndoto Quiz ===")
name = input("What is your name? ").strip() or "Player"
best = 0
while True:
score = play_round(name)
best = max(best, score)
print(f"Best score this session: {best}/{len(QUESTIONS)}")
again = input("\nPlay again? (y/n): ").strip().lower()
if again != "y":
print(f"Thanks for playing, {name}!")
break
if __name__ == "__main__":
main()
Checking only reply in LETTERS is a subtle bug. An empty reply (the player just presses Enter) gives "", and the empty string counts as being "in" every string, so "" in "ABCD" is True. Then LETTERS.index("") returns 0 and the game silently picks option A. That's why the code also checks len(reply) == 1.
random.shuffle() changes a list in place and returns None. Writing options = random.shuffle(options) sets options to None. Also, shuffling item["options"] directly would permanently reorder the master question list; the [:] copy avoids that.
Step 4: Sample run
The questions and options are shuffled every time, so your order will differ. Text after each prompt is what the player typed.
Why the design works
- Data separate from logic: to add a question you only add a dictionary to
QUESTIONS. You could even load them from a JSON file. - Small functions with one job each: asking a question, choosing a message and running a round are separate, so each is easy to test and change.
- Return values instead of global variables:
ask_question()returnsTrue/Falseandplay_round()returns the score, so no function secretly changes shared state.
While testing, add random.seed(1) at the top of main(). The "random" order will then be the same every run, which makes bugs easier to reproduce. Remove it when you're done.
Extend it
- Load questions from a file: move the questions into
questions.jsonand load them withjson.load(), so teachers can add questions without touching the code (see CSV & JSON). - Save a high-score table: store each player's name and best score in a file, and show the top five at the start of the game.
- Add a timer and categories: use
time.perf_counter()to award bonus points for fast answers, and let the player choose a category such as "Python" or "East African geography".
Key points
- Store questions as data (a list of dictionaries) and keep the logic in small functions.
- Shuffle copies, not the original list, and compare against the answer text, not the letter.
- Validate input carefully:
"" in "ABCD"isTrue. - Return values keep score cleanly without global variables.
Tip: use the ← and → keys to move between pages.
