Project: Build a Quiz Game
Combine lists, loops, if statements and functions into a complete quiz program, then learn a simple debugging routine and where to go next.
Welcome back!
Step 1 of 13Learn
Planning before typing
Every programmer has a story about starting to type before thinking, ending up with 200 tangled lines and throwing them away. Professionals plan first. For a quiz game, the plan might be:
- Store the questions and their answers.
- For each question: ask it, read the answer, compare, update the score.
- At the end, show the score and a message.
Each step maps to a tool you already know. Questions and answers fit in two lists with matching positions: the answer to questions[0] is answers[0]. Step 2 is a for loop with an if inside. The score is an accumulator. Checking one answer is a neat job for a function.
Writing the plan in plain words first, sometimes called pseudocode, helps because you solve the problem and the Python separately. If you can't explain a step in words, you won't be able to code it either.
Break big problems into small pieces you can test one at a time. Get the first question working before writing the loop. Get the loop working before adding the final message. Small working steps beat one giant leap that fails in ten places at once.
Step 2 of 13Practice · Put in order
Put these steps of the quiz plan in a sensible order.
Drag the items, or use the arrow buttons, to put them in order.
- Loop through each question
- Create the lists of questions and answers
- Set score to 0
- Ask the question and read the answer
- Print the final score
- Compare and update the score
Step 3 of 13Learn
The complete program
Here's a full version that uses every skill in the course:
questions = [
"What is 7 * 8?",
"Which planet is known as the Red Planet?",
"How many sides does a hexagon have?",
]
answers = ["56", "mars", "6"]
def check(given, correct):
return given.strip().lower() == correct
score = 0
for i in range(len(questions)):
reply = input(questions[i] + " ")
if check(reply, answers[i]):
print("Correct!")
score += 1
else:
print(f"Not quite. The answer was {answers[i]}.")
percent = score / len(questions) * 100
print(f"You scored {score}/{len(questions)} ({percent:.0f}%)")Notice the details. range(len(questions)) produces the indexes 0, 1, 2, so i can pick both the question and its matching answer. The check function strips spaces and lowercases the reply, so " Mars " and "MARS" both count. The answers are stored in lowercase so the comparison works. Answers are kept as strings, even "56", because input() returns strings.
The percentage line divides by len(questions) instead of a fixed 3. That way you can add ten more questions to the lists and every other line keeps working unchanged. Avoiding hard-coded numbers like this is one of the habits that keeps programs easy to grow.
Step 4 of 13Practice · Diagram
The quiz loop, once per question
In which step does " MARS " get treated the same as "mars"?
Tap the shape that answers the question, then press Check.
- Show questions[i]
- Read the reply
input() returns a string.
- check(reply, answers[i])
Strips spaces and lowercases before comparing.
- Update score
score += 1 if correct; show the answer if not.
Step 5 of 13Practice · Work it out
A player answers 2 of the 3 questions correctly. What whole-number percentage does the last line display?
Step 6 of 13Practice · Choose one
A player types "Mars" for the planet question. Why is it marked correct?
Step 7 of 13Practice · Code challenge · Python
Code challenge · Python
Build the scoring part of the quiz game. Complete quiz_score(replies, answers): both are lists of the same length, and answers is all lowercase. A reply counts as correct if it matches its answer after removing extra spaces and ignoring capital letters. Return the number of correct replies.
For example, quiz_score([" Mars", "7"], ["mars", "6"]) returns 1.
quiz_score([" Mars", "7"], ["mars", "6"])quiz_score(["56", "MARS ", "6"], ["56", "mars", "6"])quiz_score(["jupiter", "8"], ["mars", "6"])quiz_score([], [])
Step 8 of 13Learn
A debugging routine
Your program will have bugs. Everyone's does. What separates confident coders from frustrated ones is a routine:
- Read the error message, bottom line first. Note the error type and the line number.
- Reproduce it. Find the exact input that causes the problem.
- Print to investigate. Add temporary lines like
print("DEBUG i =", i, "reply =", repr(reply))to see what values really are.repr()shows hidden details like stray spaces or quotes. - Change one thing at a time, then run again. Changing five things at once means you won't know which one fixed it, or which one broke something else.
- Explain it out loud. Describing your code line by line to someone, or even to a rubber duck on your desk, often reveals the bug halfway through the sentence. Programmers really call this "rubber duck debugging."
Bugs that don't crash are the sneaky ones: the program runs but gives a wrong answer. Test with inputs where you already know the correct result, including edge cases like an empty answer, a zero, or the very first and last item in a list.
Step 9 of 13Diagram
The debugging routine
Tap a shape with to see more.
- Read the error
Bottom line first: error type and line number.
- Reproduce it
Find the exact input that breaks it.
- Print to investigate
print("DEBUG", repr(reply)) shows hidden spaces.
- Change one thing
Then run again.
- Explain it out loud
Rubber duck debugging.
Step 10 of 13Flashcards
Bug patterns from this course
Tap a card to flip it.
Step 11 of 13Practice · Select all that apply
Which test inputs would be most useful for checking the quiz program for hidden bugs? Select all that apply.
Select all that apply.
Step 12 of 13Note
Step 13 of 13Practice · What would you do?
What would you do?
Your quiz crashes on the last line with ZeroDivisionError: division by zero. The questions list is empty because you were testing. What's the best fix?
Lesson complete!