A quiz game is a data-driven program: questions live in a structure, and the same logic processes every one. You will build a question bank, score the answers, and report results.
What you will build#
A console quiz that:
- Stores at least five questions in a list.
- Prints each question with lettered options.
- Accepts
A,B,C, orDin either case. - Reports whether each answer is correct.
- Tracks the score.
- Prints a final summary with a percentage.
Question bank#
Each question is a dictionary with a prompt, options, the correct index, and an explanation:
questions = [
{
"prompt": "Which keyword defines a function?",
"options": ["def", "func", "function", "lambda"],
"answer": 0,
"explanation": "Functions are defined with def.",
},
{
"prompt": "What does len([1, 2, 3]) return?",
"options": ["2", "3", "4", "An error"],
"answer": 1,
"explanation": "The list contains three items.",
},
]Using zero-based indexes keeps the data simple. When you display options, convert the index to a letter with chr(ord("A") + index).
Core loop#
score = 0
for number, question in enumerate(questions, start=1):
print(f"\\nQuestion {number}: {question['prompt']}")
for index, option in enumerate(question["options"]):
letter = chr(ord("A") + index)
print(f" {letter}. {option}")
answer = input("Your answer: ").strip().upper()
correct_letter = chr(ord("A") + question["answer"])
if answer == correct_letter:
print("Correct!")
score += 1
else:
print(f"Not quite. The answer is {correct_letter}.")
print(question["explanation"])Validation#
The basic loop accepts any text and treats it as wrong. That is acceptable for a first version, but a better quiz does not penalise a typo. Add a loop that asks again until the answer is one of the valid letters:
valid = "ABCD"[: len(question["options"])]
while True:
answer = input("Your answer: ").strip().upper()
if answer in valid:
break
print(f"Choose one of {valid}.")With stdin supplied in advance, an invalid answer consumes a line and repeats the prompt. Prepare enough input lines for the retries.
Final report#
total = len(questions)
percentage = score / total * 100
print(f"\\nScore: {score}/{total} ({percentage:.0f}%)")
if percentage == 100:
print("Perfect score!")
elif percentage >= 70:
print("Good work.")
else:
print("Review the explanations and try again.")Guard against division by zero if you allow an empty question bank. Either require at least one question or handle the empty case explicitly.
Structure the program#
Move the quiz into functions:
ask_question(question, number)returnsTrueorFalse.run_quiz(questions)returns the score.print_report(score, total)prints the summary.
This makes each part testable. You can later replace console input with another source without rewriting the scoring logic.
Stretch goals#
- Add categories and let the player choose one.
- Keep a best score in a variable for repeated rounds.
- Add a time limit using
time.time(). - Print a per-category breakdown.
- Load questions from JSON text with
json.loads()and validate the structure.
Testing checklist#
- Answer every question correctly and confirm 100%.
- Answer every question incorrectly and confirm 0%.
- Enter lowercase letters.
- Enter an invalid letter and verify the retry prompt.
- Confirm the correct letter matches the intended option.
- Check the empty-bank behaviour.
