Build a Python Quiz Game
Build an interactive terminal quiz game using core Python fundamentals.
Introduction
30 Second Summary
Think about the last time you studied for a test. Quizzing yourself is one of the fastest ways to learn, but writing the questions and checking the answers gets old fast.
In this project, you will build an interactive quiz game in Python that runs right in your terminal. The program asks questions, checks your answers, tracks your score, and lets you replay as many times as you want.
What You'll Build
You run the program and your terminal turns into a quiz show, firing questions at you one by one and judging your answers on the spot.
By the end of this project, you'll have:
- A working quiz game that fires five Python trivia questions at you and tells you right away whether each answer is correct.
- A scoring system that counts your correct answers and delivers a personalized performance message based on how well you did.
- Randomized question order and a play-again loop so every round feels different without restarting the program.
- An optional Secret Mission to push your skills even further.
Before We Start
Before we write any code, let's take a moment to think about what you're building and which Python fundamentals it brings together.
Set Up Your Project
Every Python project starts with a home for your code. Before you can build the quiz game, you need a dedicated folder and a file to write in.
In this step, you'll set up your project, write a single line of Python, and run it. Seeing output in the terminal confirms that your editor and your Python installation are working together.
In this step, get ready to:
- Verify that Python is installed and ready to use.
- Create a project folder and Python file in VS Code.
- Write and run your first line of code.
Verify that Python is ready
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type VS Code and press Enter to open it.
- Open the built-in terminal by pressing Ctrl+` (backtick).
- Verify Python is installed by running the version check command for your operating system:
macOS
python3 --version
Windows
python --version
You should see a version number like Python 3.14.0 or similar.
Command not found?
On macOS, try python instead of python3 (or vice versa). Some systems use one name or the other depending on how Python was installed.
If neither works, visit the official Python downloads page and install the latest version.
Help me fix a Python command not found error
Create your project folder and file
- Move to your Desktop and create your project folder by running these commands:
cd ~/Desktop
mkdir python-quiz
- Confirm the folder was created by running:
ls
You should see python-quiz listed in the output.
Now open this folder as your VS Code workspace.
- Click File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop and select the python-quiz folder, then click Open.
Seeing a trust dialog?
VS Code may ask whether you trust the authors of the files in this folder. Click Yes, I trust the authors to continue. This is safe because you created the folder yourself.
Your VS Code workspace now shows the empty python-quiz folder in the Explorer sidebar on the left.
- Hover over the PYTHON-QUIZ heading in the Explorer sidebar and click the New File icon.
- Type quiz.py and press Enter.
The file opens in the editor, and quiz.py appears in the Explorer sidebar.
Don't see the New File icon?
Make sure you opened the python-quiz folder (not a file inside it) with File > Open Folder. The icon appears when you hover over the folder name in the Explorer sidebar.
Help me create a new file in VS Code
Write and run your first line of code
The print() function sends text to the terminal. It is the simplest way to make Python produce visible output.
- In quiz.py, type the following code:
print("Welcome to the Python Quiz!")
What does this code do?
print() takes whatever you put inside the parentheses and displays it in the terminal. The text inside the quotes is called a string. Strings are how Python represents readable text.
Before you run the file, what do you think will appear in the terminal?
- Save quiz.py by pressing Cmd+S (macOS) or Ctrl+S (Windows).
- Click the Run Python File play button in the top-right corner of the editor.
The terminal prints Welcome to the Python Quiz!. That single line proves your editor, your Python installation, and your file are all connected.
Not seeing any output?
Make sure you saved the file before clicking the play button. Unsaved changes are not picked up by Python.
Check that the file is named quiz.py (not quiz.txt or quiz). The .py extension tells VS Code to treat it as Python.
Help me run a Python file in VS Code
✔️ Awesome, I've got everything!
Great. Double check you've saved quiz.py and move on to the next step.
ⓧ I'd like to double check the full code
Here is the complete quiz.py at the end of this step:
print("Welcome to the Python Quiz!")
Your project is set up and your toolchain is working. Next up, you'll make the quiz interactive by asking a question and checking the player's answer.
Ask Your First Question
Your project folder is set up and quiz.py is running its first line of Python. Now it's time to turn that static message into something interactive.
input() captures what the player types. An if/else statement lets the program respond differently depending on whether the answer is right or wrong.
In this step, get ready to:
- Write code that asks a question and checks the player's answer.
- Test both the correct and incorrect answer paths.
Replace your welcome message with a question
Right now quiz.py prints a static welcome message. You need it to display a question, wait for the player to type their answer, and tell them whether they got it right.
- In quiz.py, select all the existing code and replace it with this:
# Ask the player a question
print("What keyword do you use to define a function in Python?")
# Capture their answer, removing extra spaces and converting to lowercase
user_answer = input("Your answer: ").strip().lower()
# Check if the answer is correct
if user_answer == "def":
print("Correct!")
else:
print("Wrong! The answer was: def")
What does this code do?
- print() displays the question in the terminal for the player to read.
- input("Your answer: ") pauses the program and waits for the player to type something. Whatever they type gets stored in user_answer.
- .strip().lower() cleans up the input by removing extra spaces and converting everything to lowercase. This way, Def, DEF, and def all count as correct.
- The if/else block compares the player's answer to "def". If it matches, the program prints "Correct!". Otherwise, it shows the right answer so the player can learn.
- Save quiz.py.
- Click the Run Python File play button in the top-right corner of the editor.
- When the terminal prints the question, type def and press Enter.
You should see Correct! printed in the terminal.
Not seeing the question?
- Make sure you saved quiz.py before running it. Unsaved changes won't execute.
- Check that you replaced all the old code. If the welcome message still appears, select everything in the file (Cmd+A on macOS, Ctrl+A on Windows) and paste the new code over it.
- Help me debug why my quiz.py isn't printing the question when I run it.
✔️ Awesome, I've got everything!
Great. Make sure you've saved quiz.py before moving on.
ⓧ I'd like to double check the full code
print("What keyword do you use to define a function in Python?")
user_answer = input("Your answer: ").strip().lower()
if user_answer == "def":
print("Correct!")
else:
print("Wrong! The answer was: def")
Test the wrong answer path
You've confirmed the correct answer path works. Before you run the quiz again, what do you think will happen if you type a wrong answer?
- Click the Run Python File play button again.
- This time, type class and press Enter.
The terminal prints Wrong! The answer was: def. Both branches of your if/else statement are working.
Your quiz can ask one question and check the answer. In the next step, you'll build a question bank so you can add as many questions as you want without duplicating code.
Build a Question Bank
Your quiz can ask a question and check the answer. That is a great start, but a one-question quiz is not much of a game.
Imagine adding ten more questions. You would have to copy-paste the same if/else block ten times and hardcode every question string. That is repetitive, error-prone, and painful to update. In this step, you will store all your questions in one organized data structure and let a loop ask them automatically.
In this step, get ready to:
- Store five Python trivia questions in a list of dictionaries.
- Loop through each question to ask it, number it, and check the answer.
Store your questions in a list
A list in Python holds multiple items in order. A dictionary holds key-value pairs, like a mini database entry. By combining them, you can store each question alongside its correct answer in one tidy package.
- Select all the code in quiz.py by pressing Cmd+A (macOS) or Ctrl+A (Windows) and delete it.
- Replace it with this question bank:
# Each dictionary holds one question and its correct answer
questions = [
{
"question": "What keyword do you use to define a function in Python?",
"answer": "def"
},
{
"question": "What built-in function do you use to get the length of a list?",
"answer": "len"
},
{
"question": "What data type do you use to store True or False values?",
"answer": "bool"
},
{
"question": "What symbol do you use to start a comment in Python?",
"answer": "#"
},
{
"question": "What keyword do you use to create a loop that repeats for each item in a list?",
"answer": "for"
},
]
What does this code do?
questions is a list (the square brackets []) that holds five dictionaries (the curly braces {}). Each dictionary has two keys:
- "question" stores the text the player sees.
- "answer" stores the correct response to check against.
To add or remove a question later, you just edit this one list. No copy-pasting if/else blocks required.
- Save quiz.py and run it by clicking the play button in the top-right corner of the editor.
- The terminal returns to the prompt with no error messages. That confirms Python can read your question bank without any syntax issues.
Seeing a SyntaxError?
- Check that every opening brace { has a matching closing brace } and every opening bracket [ has a matching closing bracket ].
- Make sure there is a comma after each closing brace }, except the very last one (which has a trailing comma before the ]).
- Confirm you deleted all of the old single-question code before pasting the new list.
Help me fix a SyntaxError in my Python list of dictionaries.
Loop through the question bank
The question bank is ready, but nothing prints yet because there is no code to read through it. A for loop will walk through each dictionary in the list, pull out the question, ask the player, and check the answer.
- Below the closing ] of the questions list, add a blank line and then paste this loop:
# Loop through each question with a number starting at 1
for i, q in enumerate(questions, 1):
print(f"Question {i}: {q['question']}")
user_answer = input("Your answer: ").strip().lower()
# Check if the answer matches (case-insensitive)
if user_answer == q["answer"].lower():
print("Correct!\n")
else:
print(f"Wrong! The answer was: {q['answer']}\n")
What does this code do?
- enumerate(questions, 1) loops through the list and gives each item a number, starting at 1 instead of the default 0. The number goes into i and the dictionary goes into q.
- .strip().lower() cleans up the player's input by removing extra spaces and converting everything to lowercase. This way, Def, DEF, and def all count as correct.
- The f"..." strings are f-strings. They let you drop variables directly into text using curly braces, so f"Question {i}" becomes Question 1 on the first pass.
Before you run the quiz, think about what you expect to see. How many questions will appear? Will they be numbered?
- Save quiz.py and run it by clicking the play button.
- Answer all five questions in the terminal. Try getting some right and some wrong.
The program asks all five questions one after another, numbering them Question 1 through Question 5. After each answer, it prints Correct! or Wrong! The answer was: ... depending on what you typed.
Only seeing one question or getting a NameError?
- If nothing prints at all, make sure the for loop is outside and below the questions list, not inside it.
- If you see a NameError mentioning questions, check that the variable name is spelled exactly as questions in both the list and the loop.
- Make sure the lines inside the for loop are indented with four spaces. Python uses indentation to know which lines belong to the loop.
Help me debug my Python quiz loop.
✔️ Awesome, I've got everything!
Great. Double check you have saved quiz.py and all five questions appeared in the terminal.
ⓧ I'd like to double check the full code
Scroll up through your quiz.py and confirm it has both of these sections in this exact order:
- The questions list containing five dictionaries, each with a "question" key and an "answer" key.
- The for i, q in enumerate(questions, 1): loop that prints each question, captures input with .strip().lower(), and checks the answer with an if/else block.
Make sure there is a blank line between the closing ] of the list and the start of the for loop.
Your quiz now has a full question bank and a loop that runs through every question automatically. Next up, you will add a scoring system so the player knows how they did at the end.
Track the Score
Your quiz now fires off all five questions and judges each answer on the spot. But once the last question finishes, the program just stops. The player has no idea how they performed overall.
In this step, you will add a score counter that tracks correct answers as the quiz runs. After the last question, your program will print a final tally and a performance message that changes based on how well the player did.
In this step, get ready to:
- Track correct answers with a score variable that increments inside the loop.
- Display a final score and a conditional performance message after the quiz ends.
Add a score counter
Right now, the quiz says "Correct!" or "Wrong!" for each question but forgets the result immediately. You need a variable that starts at zero and goes up by one every time the player gets an answer right.
- In quiz.py, find the for loop line.
- Add score = 0 on a blank line above it, so it looks like this:
# Set the starting score before the quiz begins
score = 0
for i, q in enumerate(questions, 1):
- Now scroll down inside the if block. Find the line print("Correct!\n").
- Add score += 1 on the next line, at the same indent level. Then, after the entire for loop ends (below the else block), add a line that prints the final score:
if user_answer == q["answer"].lower():
print("Correct!\n")
# Add one point for a correct answer
score += 1
else:
print(f"Wrong! The answer was: {q['answer']}\n")
# Show the final tally after all questions are done
print(f"You scored {score} out of {len(questions)}!")
What does this code do?
- score = 0 creates a counter before the loop starts. Every variable you want to accumulate across a loop needs to be initialized before the loop begins.
- score += 1 is shorthand for score = score + 1. It only runs inside the if branch, so only correct answers add a point.
- The f-string at the end plugs the final score and len(questions) values into the output string so the player sees something like "You scored 3 out of 5!".
- Save quiz.py.
- Run your program by clicking the play button in the top-right corner of the editor.
- Answer all five questions. After the last one, you should see your score printed (e.g. You scored 4 out of 5!).
Not seeing a score at the end?
- Make sure the print(f"You scored...") line is outside the for loop. It should have no indentation (flush left). If it is indented, it will print after every question instead of once at the end.
- Check that score = 0 is above the for loop, not inside it. Placing it inside the loop would reset the score to zero on every question.
- If your score always shows 0, confirm that score += 1 is inside the if block (indented under it), not under the else.
Still stuck? Ask for help.
Add performance messages
The score line tells the player how many they got right, but it lands the same way whether they aced the quiz or missed every question. A conditional message that reacts to their score makes the ending feel personal.
- In quiz.py, find the score print line you just added. Add this if/elif/else block right below it:
# Give different feedback depending on how the player did
if score == len(questions):
print("Perfect score! You're a Python pro!")
elif score >= len(questions) // 2:
print("Nice job! You're getting the hang of it!")
else:
print("Keep practicing, you'll get there!")
What does this code do?
- The if branch checks whether score equals the total number of questions. If so, every answer was correct.
- The elif branch uses // (integer division) to calculate half the total. Getting at least half right earns a "nice job" message.
- The else catches everyone below half. Python checks each condition top to bottom and runs only the first one that matches.
- Save quiz.py.
Before you run the quiz, think about this: if you answer exactly 3 out of 5 correctly, which performance message do you think will print?
- Run your program by clicking the play button.
- Answer all five questions.
After the last question, the terminal prints your score (e.g. You scored 4 out of 5!) followed by a performance message that matches how you did. Try running it a second time and deliberately get fewer than half right to see the encouraging message.
Performance message not showing up?
- Make sure the if/elif/else block is below the score print line and has no indentation (flush left). If it is indented under the for loop, Python will try to evaluate it on every question instead of once at the end.
- Check for a colon at the end of each condition line (if score == len(questions):). A missing colon causes a syntax error.
Still stuck? Ask for help.
✔️ Awesome, I've got everything!
Great. Double check you have saved quiz.py before moving on.
ⓧ I'd like to double check the full code
Your quiz.py should contain these sections in order. Scroll up through the file and confirm each one is present.
- The questions list containing five dictionaries, each with a "question" and "answer" key.
- score = 0 on its own line, before the for loop.
- The for loop with enumerate(questions, 1), the input/answer check, and score += 1 inside the if block.
- The score print line: print(f"You scored {score} out of {len(questions)}!") after the loop.
- The if/elif/else block that prints a performance message based on the score.
Your quiz now gives the player a proper ending with a score and a personalized message. Next up, you will shuffle the question order so every playthrough feels fresh and add a play-again loop so the player can keep going without restarting the program.
Shuffle and Replay
Your quiz works, but try playing it a second time. The questions always appear in the exact same order, which makes every replay feel like a rerun.
In this step, you'll fix that by importing Python's random module to shuffle the question order. You'll also wrap all the quiz logic inside a function so it can be called more than once, and add a play-again loop so the player can keep going without restarting the program.
In this step, get ready to:
- Wrap all quiz logic inside a run_quiz() function and shuffle the question order.
- Create a main() function with a play-again loop.
- Verify that questions shuffle each playthrough and the replay prompt works.
Wrap the quiz logic in a function and shuffle questions
A function is a reusable block of code you can call by name. Right now, your quiz code runs once from top to bottom and stops. By wrapping it inside a function called run_quiz(), you can call that function whenever you want to start a new round.
- In quiz.py, delete all the existing code and replace it with this code:
import random
def run_quiz():
questions = [
{
"question": "What keyword do you use to define a function in Python?",
"answer": "def"
},
{
"question": "What built-in function do you use to get the length of a list?",
"answer": "len"
},
{
"question": "What data type do you use to store True or False values?",
"answer": "bool"
},
{
"question": "What symbol do you use to start a comment in Python?",
"answer": "#"
},
{
"question": "What keyword do you use to create a loop that repeats for each item in a list?",
"answer": "for"
},
]
What does this code do?
- import random loads Python's built-in random module, which gives you tools for randomization. You'll use it in a moment to shuffle the question order.
- def run_quiz(): defines a function called run_quiz. Everything indented beneath it belongs to that function and only runs when you call run_quiz().
- The questions list is the same one you built in the previous step. It now lives inside the function so it gets created fresh each time the quiz runs.
- Continue building run_quiz() by adding this code directly below the questions list:
print("Welcome to the Python Quiz!")
print(f"You'll be asked {len(questions)} questions. Let's go!\n")
random.shuffle(questions)
score = 0
for i, q in enumerate(questions, 1):
print(f"Question {i}: {q['question']}")
user_answer = input("Your answer: ").strip().lower()
if user_answer == q["answer"].lower():
print("Correct!\n")
score += 1
else:
print(f"Wrong! The answer was: {q['answer']}\n")
print(f"You scored {score} out of {len(questions)}!")
if score == len(questions):
print("Perfect score! You're a Python pro!")
elif score >= len(questions) // 2:
print("Nice job! You're getting the hang of it!")
else:
print("Keep practicing, you'll get there!")
What's new in this code?
Most of this code is the same for loop, scoring, and feedback you already wrote. The three new lines are the important ones.
- The two print() lines at the top display a welcome message and tell the player how many questions are coming.
- random.shuffle(questions) rearranges the questions list into a random order. It modifies the list directly and does not return a new one.
The function is complete, but nothing calls it yet. The code won't run until you tell Python to execute run_quiz().
- At the very bottom of quiz.py, add two blank lines after the last line of run_quiz(), then add this line (with no indentation) to call the function:
run_quiz()
Before you run the program, think about this: will the questions appear in the same order as before, or a different order? Why?
- Save quiz.py.
- Run the program by clicking the Run Python File play button in the top-right corner of the editor.
The terminal prints "Welcome to the Python Quiz!" followed by the question count, then asks all five questions. The question order is now randomized thanks to random.shuffle().
Seeing a NameError or IndentationError?
- If you see NameError: name 'run_quiz' is not defined, make sure the run_quiz() call at the bottom has no indentation. It must sit at the leftmost edge of the file, outside the function.
- If you see an IndentationError, check that every line inside def run_quiz(): is indented by exactly four spaces. Mixing tabs and spaces causes this error.
- Make sure import random is on the very first line of the file with no indentation.
Why is my quiz function not running?
Add a play-again loop
The quiz shuffles and works, but it still ends after one playthrough. A while loop can keep the program running until the player decides to stop. You'll wrap the quiz call inside a main() function that handles replay.
- In quiz.py, find the run_quiz() call at the very bottom of the file.
- Find this line:
run_quiz()
- Replace it with this code:
def main():
# Control the game loop with a boolean flag
playing = True
while playing:
run_quiz()
play_again = input("\nWould you like to play again? (yes/no): ").strip().lower()
if play_again != "yes":
print("Thanks for playing!")
playing = False
else:
print()
main()
What does this code do?
- playing = True creates a boolean flag that controls whether the loop keeps running.
- while playing: starts a loop that repeats as long as playing is True. Each pass calls run_quiz() for a full round.
- After each round, input() asks the player if they want to go again. Typing anything other than "yes" sets playing to False, which stops the loop.
- main() at the very bottom (outside both functions, no indentation) kicks everything off when you run the file.
Why a main() function?
You could write the while loop at the top level of the file without a function. Wrapping it in main() is a common Python pattern that keeps your program's entry point clearly labeled. It also keeps all your logic inside functions, making the code easier to read and extend later.
Before you run the program, predict what will happen when you type "yes" at the play-again prompt. Will the questions appear in the same order as the first round?
- Save quiz.py and run the program by clicking the Run Python File play button.
- Play through the quiz once, then type yes at the play-again prompt to start a second round.
- After the second round, type no to confirm the program ends with "Thanks for playing!".
The questions appear in a different order each time you play. Typing "yes" restarts the quiz with a fresh shuffle, and typing anything else ends the program.
Quiz doesn't restart or questions aren't shuffling?
- If the program ends immediately without asking to play again, make sure main() (the call, not the function definition) is at the very bottom of the file with no indentation.
- If typing "yes" does not restart the quiz, check that run_quiz() is indented inside the while playing: loop, not outside it.
- If the questions appear in the same order every time, confirm that random.shuffle(questions) is inside run_quiz() and runs before the for loop.
Why isn't my play-again loop working?
✔️ Awesome, I've got everything!
Great. Double check that you've saved quiz.py.
ⓧ I'd like to double check the full code
Scroll up through your quiz.py file and confirm each section is present, in this order:
- import random at the very top of the file.
- def run_quiz(): containing the questions list, two welcome print() calls, random.shuffle(questions), the for loop with scoring, and the if/elif/else performance message.
- def main(): with a while playing: loop that calls run_quiz() and handles the play-again prompt.
- main() on the last line with no indentation.
Your quiz game is fully functional. It shuffles, scores, gives feedback, and lets the player replay as many times as they want. Next up, the Secret Mission challenges you to add multiple-choice options to make the game even more polished.
Secret mission
Add Multiple Choice
Your quiz works, but free-text answers can be unforgiving. A player might know the right concept but type it slightly differently. Ready to add A/B/C/D multiple-choice options that shuffle every time?
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely locally, so there are no ongoing costs. Decide whether to keep your project files, or delete them entirely.
Resources you used:
- python-quiz folder on your Desktop containing quiz.py.
Keep everything running
No action needed. Choose this if you want to keep building on your quiz game or revisiting the code.
- Your python-quiz folder stays on your Desktop, ready to open in VS Code any time.
- No background processes are running. The quiz only runs when you execute quiz.py.
Pause - I'll come back to this later
Since this project is entirely local with no running processes, there is nothing to pause. Your files sit on disk and use no memory or CPU while idle.
- Leave the python-quiz folder on your Desktop. It will be there when you're ready to return.
- To pick up where you left off, open VS Code and use File > Open Folder to reopen the python-quiz folder.
Delete - I don't want to use this again
Remove the project folder to start fresh. This permanently deletes your quiz code.
- Close the python-quiz folder in VS Code if it is still open.
- On macOS or Linux, open a terminal and run:
rm -rf ~/Desktop/python-quiz
- On Windows, open a terminal and run:
rmdir /s /q %USERPROFILE%\Desktop\python-quiz
- Confirm the folder is gone by checking your Desktop. You should no longer see a python-quiz folder.
Nice Work!
Nice Work!
You just built a fully interactive quiz game from scratch using Python. Every core building block you practiced here (variables, conditionals, loops, lists, dictionaries, and functions) is something you will use in virtually every Python program you write from here on.
Here's what you accomplished:
- Built an interactive command-line game that uses input() and print() to have a real-time conversation with the player, and if/elif/else conditionals to check answers and deliver personalized feedback.
- Stored five questions in a list of dictionaries and looped through them with a for loop and enumerate(), tracking a running score across the entire quiz.
- Organized the game into reusable functions (run_quiz() and main()), randomized question order with random.shuffle(), and added a while loop so the player can replay without restarting the program.
- Completed an optional Secret Mission to push your skills even further.
Ready to quiz yourself?