Build a Quiz Game with Python
Build an interactive terminal quiz game using Python fundamentals.
Introduction
30 Second Summary
Quizzes are everywhere. From classroom pop quizzes to trivia nights with friends, they test what you know and keep things fun. What if you could build your own quiz from scratch, with custom questions and instant scoring?
In this project, you will build an interactive quiz game using Python that runs right in your terminal. You'll create questions, collect answers, and display a final score.
What You'll Build
A terminal-based quiz game that presents multiple-choice questions in a random order, validates player input, tracks the score, and displays results with feedback at the end.
By the end of this project, you'll have:
- A Python script (quiz.py) that runs an interactive quiz game in the terminal.
- A data structure of quiz questions built with lists and dictionaries.
- Reusable functions that handle question display, answer validation, and scoring with formatted output.
- Secret Mission: Add a countdown timer and replay functionality so players can challenge themselves to beat their best time.
Are there any prerequisites?
None at all. This project is designed for complete beginners. Step 1 walks you through installing Python and Visual Studio Code from scratch.
Install Python and VS Code
Every Python project starts with a file. For our quiz game, we need a single Python script that holds all the game logic and question data.
We'll store each question as a Python dictionary with the question text, answer choices, and the correct answer. Then we'll group all the questions into a list that our game can loop through.
In this step, get ready to:
- Create a quiz.py file inside a new project folder.
- Import the random module.
- Build a get_questions() function with five quiz questions.
Create your project folder and file
Before writing any code, you need a dedicated folder for your project and a Python file inside it.
- Return to the terminal in Visual Studio Code.
- Move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder by running this command:
mkdir python-quiz
- Confirm the folder was created by running:
ls
You should see python-quiz in the output.
- Move into your new project folder by running:
cd python-quiz
Now you need to open this folder in VS Code and create your Python file.
- In VS Code, click File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop, select the python-quiz folder, and click Open (macOS) or Select Folder (Windows).
- In the Explorer sidebar on the left, hover over the folder name and click the New File icon (a page with a plus sign).
- Type quiz.py and press Enter.
VS Code opens the empty quiz.py file in the editor, ready for your code.
Don't see the Explorer sidebar?
If the sidebar is hidden, press Cmd+B (macOS) or Ctrl+B (Windows) to toggle it back on.
If VS Code asks whether you trust the authors of the folder, click Yes, I trust the authors to continue.
Help me find the Explorer sidebar in VS Code
Add the quiz question data
Our quiz game needs two things to start: a way to randomize question order, and the questions themselves. Python's random module handles shuffling. A function will organize all our question data in one place.
- Add the following code to your empty quiz.py file:
import random
def get_questions():
# Store all quiz questions as a list of dictionaries
questions = [
{
"question": "What is the capital of France?",
"options": ["London", "Berlin", "Paris", "Madrid"],
"answer": "Paris",
},
{
"question": "Which planet is known as the Red Planet?",
"options": ["Venus", "Mars", "Jupiter", "Saturn"],
"answer": "Mars",
},
{
"question": "What is the largest ocean on Earth?",
"options": ["Atlantic", "Indian", "Arctic", "Pacific"],
"answer": "Pacific",
},
{
"question": "Who painted the Mona Lisa?",
"options": ["Van Gogh", "Da Vinci", "Picasso", "Rembrandt"],
"answer": "Da Vinci",
},
{
"question": "What is the chemical symbol for water?",
"options": ["H2O", "CO2", "NaCl", "O2"],
"answer": "H2O",
},
]
return questions
What does this code do?
- import random brings in Python's built-in randomization tools. You'll use this later to shuffle the question order.
- get_questions() is a function that returns a list of dictionaries. Each dictionary represents one quiz question.
- Every question dictionary has three keys: "question" (the text to display), "options" (a list of four choices), and "answer" (the correct choice).
- return questions sends the full list back to whatever code calls this function.
- Save quiz.py by pressing Cmd+S (macOS) or Ctrl+S (Windows).
- Open the integrated terminal by pressing Ctrl+` (backtick key, on both macOS and Windows).
- Verify your code has no errors by running:
python quiz.py
You should see no output and no errors. The script runs silently because you defined a function but haven't called it yet.
Seeing a syntax error?
- Check that all brackets and quotes are paired. Each dictionary uses curly braces {} inside square brackets [].
- Make sure each dictionary entry ends with a comma after the closing },.
- Confirm you're using straight quotes " and not curly/smart quotes.
Help me fix a syntax error in my quiz.py file
✔️ Awesome, I've got everything!
Great job. Double check you've saved quiz.py before moving on.
ⓧ I'd like to double check the full code
Here's the complete quiz.py file so far. Make sure yours matches exactly:
import random
def get_questions():
questions = [
{
"question": "What is the capital of France?",
"options": ["London", "Berlin", "Paris", "Madrid"],
"answer": "Paris",
},
{
"question": "Which planet is known as the Red Planet?",
"options": ["Venus", "Mars", "Jupiter", "Saturn"],
"answer": "Mars",
},
{
"question": "What is the largest ocean on Earth?",
"options": ["Atlantic", "Indian", "Arctic", "Pacific"],
"answer": "Pacific",
},
{
"question": "Who painted the Mona Lisa?",
"options": ["Van Gogh", "Da Vinci", "Picasso", "Rembrandt"],
"answer": "Da Vinci",
},
{
"question": "What is the chemical symbol for water?",
"options": ["H2O", "CO2", "NaCl", "O2"],
"answer": "H2O",
},
]
return questions
Your quiz data is ready. Next up, you'll write the function that presents these questions to the player and collects their answers.
Create Your Quiz Data
Your quiz questions are stored as a list of dictionaries, each holding the question text, answer options, and correct answer. This structure makes it easy to loop through questions and check answers.
Now you need a way to actually present those questions to the player. In this step, you'll build a function that displays questions, collects player input, validates it, and gives instant feedback.
In this step, get ready to:
- Write a function that displays questions with numbered options.
- Add input validation so only answers 1-4 are accepted.
- Check answers and print feedback telling the player if they're correct.
Write the ask_question function
Your quiz needs a function that handles the entire flow for a single question: display it, get valid input from the player, and tell them whether they got it right. This function will be called once for each question in the quiz.
- In quiz.py, find the end of your get_questions() function (the return questions line).
- Below that function, add the following code to create your ask_question() function:
def ask_question(question_data, question_number):
# Display the question number and text
print(f"\nQuestion {question_number}:")
print(question_data["question"])
# Print each answer option with a number
options = question_data["options"]
for i, option in enumerate(options, 1):
print(f" {i}. {option}")
# Keep asking until the player enters a valid answer
while True:
user_input = input("\nYour answer (1-4): ")
if user_input in ["1", "2", "3", "4"]:
break
print("Please enter a number between 1 and 4.")
# Check if the selected answer matches the correct one
selected_answer = options[int(user_input) - 1]
correct = selected_answer == question_data["answer"]
# Give the player feedback
if correct:
print("Correct!")
else:
print(f"Wrong! The answer was: {question_data['answer']}")
return correct
What does this code do?
This function handles the full lifecycle of a single quiz question. It takes in one question dictionary and its position number.
- enumerate(options, 1) pairs each option with a counter starting at 1, so the player sees options numbered 1 through 4 instead of 0 through 3.
- The while True loop keeps prompting the player until they type a valid number (1-4). The break keyword exits the loop once a valid answer arrives.
- options[int(user_input) - 1] converts the player's choice (a string like "2") into a list index. Subtracting 1 accounts for lists starting at position 0.
- The function returns True or False so the calling code can track the score without knowing the details of how questions work.
What is enumerate?
enumerate() is a built-in Python function that gives you both a counter and the value when looping through a list. The 1 argument tells it to start counting at 1 instead of the default 0.
- Save quiz.py.
- Open your terminal in VS Code by pressing Ctrl+` (macOS and Windows).
- Run your script to check for syntax errors by running:
python quiz.py
- You should see no output and no error messages. This confirms Python read your function definitions without any syntax issues.
Seeing a SyntaxError or IndentationError?
- Check that every line inside the function is indented with 4 spaces. Python uses indentation to know which lines belong to the function.
- Make sure the while True: block has its contents indented 8 spaces total (4 for the function, 4 for the loop).
- Verify that f-strings use matching quote types. The line f"Wrong! The answer was: {question_data['answer']}" uses double quotes on the outside and single quotes inside the curly braces.
Help me fix a Python indentation or syntax error in my ask_question function
✔️ Awesome, I've got everything!
Great. Double check you've saved your file before moving on.
ⓧ I'd like to double check the full code
Here's what your full quiz.py file should look like at this point:
import random
def get_questions():
questions = [
{
"question": "What is the capital of France?",
"options": ["London", "Berlin", "Paris", "Madrid"],
"answer": "Paris",
},
{
"question": "Which planet is known as the Red Planet?",
"options": ["Venus", "Mars", "Jupiter", "Saturn"],
"answer": "Mars",
},
{
"question": "What is the largest ocean on Earth?",
"options": ["Atlantic", "Indian", "Arctic", "Pacific"],
"answer": "Pacific",
},
{
"question": "Who painted the Mona Lisa?",
"options": ["Van Gogh", "Da Vinci", "Picasso", "Rembrandt"],
"answer": "Da Vinci",
},
{
"question": "What is the chemical symbol for water?",
"options": ["H2O", "CO2", "NaCl", "O2"],
"answer": "H2O",
},
]
return questions
def ask_question(question_data, question_number):
print(f"\nQuestion {question_number}:")
print(question_data["question"])
options = question_data["options"]
for i, option in enumerate(options, 1):
print(f" {i}. {option}")
while True:
user_input = input("\nYour answer (1-4): ")
if user_input in ["1", "2", "3", "4"]:
break
print("Please enter a number between 1 and 4.")
selected_answer = options[int(user_input) - 1]
correct = selected_answer == question_data["answer"]
if correct:
print("Correct!")
else:
print(f"Wrong! The answer was: {question_data['answer']}")
return correct
Your function can now display a question, validate the player's input, and check their answer. Next up, you'll wire everything together into a full game loop that tracks the score across all questions.
Display Questions and Collect Answers
In the previous step, you set up your quiz questions and built a function that can display a single question and check the player's answer. Now it's time to tie everything together into a playable game.
You'll write a run_quiz() function that shuffles the questions into a random order, loops through them one by one, tracks the score, and displays the final results. This is where your quiz transforms from isolated parts into a complete experience.
In this step, get ready to:
- Build a game loop that shuffles and presents all your questions.
- Calculate and display the final score as a percentage.
- Add performance-based feedback messages.
Write the run_quiz() function
Your ask_question() function handles one question at a time. The run_quiz() function orchestrates the entire game: it fetches questions, randomizes their order, loops through each one, and keeps a running score.
- In quiz.py, scroll to the bottom of the file (below your ask_question() function).
- Add the following run_quiz() function and function call by copying this code at the bottom of your file:
def run_quiz():
# Print a welcome banner
print("=" * 40)
print(" WELCOME TO THE PYTHON QUIZ GAME!")
print("=" * 40)
# Get questions and shuffle them into a random order
questions = get_questions()
random.shuffle(questions)
# Initialize score tracking
score = 0
total = len(questions)
# Loop through each question and track correct answers
for i, question in enumerate(questions, 1):
if ask_question(question, i):
score += 1
# Print the results banner
print("\n" + "=" * 40)
print(" QUIZ COMPLETE!")
print("=" * 40)
percentage = (score / total) * 100
print(f"\nYour score: {score}/{total} ({percentage:.0f}%)")
# Give feedback based on performance
if percentage == 100:
print("Perfect score! You're a genius!")
elif percentage >= 60:
print("Great job! Well done!")
else:
print("Keep learning! You'll do better next time!")
run_quiz()
What does this code do?
This function has three main sections:
- The game setup calls get_questions() to fetch your question list, then random.shuffle(questions) rearranges them in place so the order is different each time you play.
- The game loop uses enumerate(questions, 1) to loop through questions with a counter starting at 1. Each time ask_question() returns True, the score goes up by 1.
- The results section calculates the percentage with (score / total) * 100, formats it with :.0f (zero decimal places), and uses if/elif/else to pick a message based on how well the player did.
The final run_quiz() line at the very bottom (outside the function) is what actually starts the game when you run the script.
Run your quiz game
- Save quiz.py.
- Open the terminal in VS Code by pressing Ctrl+` (the backtick key, above Tab).
- Run your quiz by entering this command:
python quiz.py
Your quiz starts with a welcome banner, then presents 5 questions in a random order. Answer each one by typing a number from 1 to 4. At the end, you'll see your score and a feedback message.
What should I see?
You should see a banner that says WELCOME TO THE PYTHON QUIZ GAME! followed by your first question with four numbered options.
After answering all 5 questions, you'll see QUIZ COMPLETE! with your score displayed as both a fraction and a percentage, plus a feedback message.
Seeing a NameError or nothing happening?
- Make sure run_quiz() (the function call) is at the very bottom of your file with no indentation. If it's indented, Python thinks it's inside the function definition and won't execute it.
- Check that def run_quiz(): is below def ask_question(): in your file. Python reads top to bottom, so functions must be defined before they're called.
- If you see ModuleNotFoundError, confirm that import random is still at the very top of your file.
Why isn't my quiz running when I type python quiz.py?
✔️ Awesome, I've got everything!
Great. Double check you've saved quiz.py and that the quiz runs successfully when you enter python quiz.py in the terminal.
ⓧ I'd like to double check the full code
Here's the complete quiz.py file at the end of this step:
import random
def get_questions():
questions = [
{
"question": "What is the capital of France?",
"options": ["London", "Berlin", "Paris", "Madrid"],
"answer": "Paris",
},
{
"question": "Which planet is known as the Red Planet?",
"options": ["Venus", "Mars", "Jupiter", "Saturn"],
"answer": "Mars",
},
{
"question": "What is the largest ocean on Earth?",
"options": ["Atlantic", "Indian", "Arctic", "Pacific"],
"answer": "Pacific",
},
{
"question": "Who painted the Mona Lisa?",
"options": ["Van Gogh", "Da Vinci", "Picasso", "Rembrandt"],
"answer": "Da Vinci",
},
{
"question": "What is the chemical symbol for water?",
"options": ["H2O", "CO2", "NaCl", "O2"],
"answer": "H2O",
},
]
return questions
def ask_question(question_data, question_number):
print(f"\nQuestion {question_number}:")
print(question_data["question"])
options = question_data["options"]
for i, option in enumerate(options, 1):
print(f" {i}. {option}")
while True:
user_input = input("\nYour answer (1-4): ")
if user_input in ["1", "2", "3", "4"]:
break
print("Please enter a number between 1 and 4.")
selected_answer = options[int(user_input) - 1]
correct = selected_answer == question_data["answer"]
if correct:
print("Correct!")
else:
print(f"Wrong! The answer was: {question_data['answer']}")
return correct
def run_quiz():
print("=" * 40)
print(" WELCOME TO THE PYTHON QUIZ GAME!")
print("=" * 40)
questions = get_questions()
random.shuffle(questions)
score = 0
total = len(questions)
for i, question in enumerate(questions, 1):
if ask_question(question, i):
score += 1
print("\n" + "=" * 40)
print(" QUIZ COMPLETE!")
print("=" * 40)
percentage = (score / total) * 100
print(f"\nYour score: {score}/{total} ({percentage:.0f}%)")
if percentage == 100:
print("Perfect score! You're a genius!")
elif percentage >= 60:
print("Great job! Well done!")
else:
print("Keep learning! You'll do better next time!")
run_quiz()
Your quiz game is fully playable. Next up, you'll take on the Secret Mission and add a countdown timer plus replay functionality to make it even more engaging.
Build the Game Loop and Scoring
Your questions are defined and your ask_question() function handles displaying them and collecting answers.
The final piece is the game loop. Your run_quiz() function orchestrates the entire quiz experience by shuffling questions, looping through them, tracking your score, and delivering feedback at the end.
In this step, get ready to:
- Walk through how the game loop orchestrates the quiz.
- Run the complete quiz game in your terminal.
- Verify the scoring and feedback messages work correctly.
Walk through the game loop
The run_quiz() function at the bottom of your file is the conductor of your quiz game. It coordinates every other piece you have built so far.
- In VS Code, scroll down to the run_quiz() function in your quiz.py file.
- Read through the function to see how it connects everything together.
What does run_quiz() do?
This function handles the full game flow in five stages:
- print("=" * 40) creates a visual welcome banner so the player knows the game has started.
- random.shuffle(questions) randomizes the question order every time you play.
- The for loop with enumerate() iterates through each question and passes it to ask_question().
- score += 1 only triggers when ask_question() returns True (correct answer).
- The final section calculates the percentage and prints a message based on performance.
Why shuffle the questions?
random.shuffle() rearranges the list in place, so the questions appear in a different order every time. This makes the quiz replayable and prevents players from memorizing the sequence instead of the answers.
Run the complete quiz game
Your quiz game is fully assembled. Time to play it and see everything working together.
- Run the quiz game by entering this command in your terminal:
macOS
python3 quiz.py
Windows
python quiz.py
What should I see?
The game starts with a welcome banner made of = characters. Then questions appear one at a time with four numbered options.
Type a number between 1 and 4 and press Enter to answer each question. If you type anything else, the game asks you to try again.
- Answer all 5 questions to complete the quiz.
- After the last question, you should see a completion banner, your score as a fraction and percentage, and a feedback message.
Not seeing any output?
Make sure you saved quiz.py before running the command.
Check that your terminal is open in the same folder where quiz.py lives. You can verify by running ls (macOS) or dir (Windows) and looking for quiz.py in the output.
help me debug why my Python quiz game isn't producing output when I run it
Verify the scoring and feedback messages
Your quiz has three different feedback messages depending on how well the player does. The conditional logic at the end of run_quiz() checks the percentage and picks the right message.
What are the three score paths?
- 100% correct: "Perfect score! You're a genius!"
- 60% or higher: "Great job! Well done!"
- Below 60%: "Keep learning! You'll do better next time!"
The if/elif/else chain checks the most specific condition first (perfect) and falls through to the general case (below 60%). This pattern is called a conditional chain.
- Run the quiz again and deliberately answer some questions wrong to see a different feedback message.
- Notice that the questions appear in a different order this time thanks to random.shuffle().
✔️ Awesome, I've got everything!
Great. Double check you have saved your quiz.py file and that your game runs without errors.
ⓧ I'd like to double check the full code
Here is the complete quiz.py file. Compare it with yours to make sure everything matches.
import random
def get_questions():
questions = [
{
"question": "What is the capital of France?",
"options": ["London", "Berlin", "Paris", "Madrid"],
"answer": "Paris",
},
{
"question": "Which planet is known as the Red Planet?",
"options": ["Venus", "Mars", "Jupiter", "Saturn"],
"answer": "Mars",
},
{
"question": "What is the largest ocean on Earth?",
"options": ["Atlantic", "Indian", "Arctic", "Pacific"],
"answer": "Pacific",
},
{
"question": "Who painted the Mona Lisa?",
"options": ["Van Gogh", "Da Vinci", "Picasso", "Rembrandt"],
"answer": "Da Vinci",
},
{
"question": "What is the chemical symbol for water?",
"options": ["H2O", "CO2", "NaCl", "O2"],
"answer": "H2O",
},
]
return questions
def ask_question(question_data, question_number):
print(f"\nQuestion {question_number}:")
print(question_data["question"])
options = question_data["options"]
for i, option in enumerate(options, 1):
print(f" {i}. {option}")
while True:
user_input = input("\nYour answer (1-4): ")
if user_input in ["1", "2", "3", "4"]:
break
print("Please enter a number between 1 and 4.")
selected_answer = options[int(user_input) - 1]
correct = selected_answer == question_data["answer"]
if correct:
print("Correct!")
else:
print(f"Wrong! The answer was: {question_data['answer']}")
return correct
def run_quiz():
print("=" * 40)
print(" WELCOME TO THE PYTHON QUIZ GAME!")
print("=" * 40)
questions = get_questions()
random.shuffle(questions)
score = 0
total = len(questions)
for i, question in enumerate(questions, 1):
if ask_question(question, i):
score += 1
print("\n" + "=" * 40)
print(" QUIZ COMPLETE!")
print("=" * 40)
percentage = (score / total) * 100
print(f"\nYour score: {score}/{total} ({percentage:.0f}%)")
if percentage == 100:
print("Perfect score! You're a genius!")
elif percentage >= 60:
print("Great job! Well done!")
else:
print("Keep learning! You'll do better next time!")
run_quiz()
Secret mission
Add a Timer and Replay
Your quiz game works, but what if players want to challenge themselves to answer faster? Or play multiple rounds without restarting the program? In this secret mission, you'll add a countdown timer that tracks how long each attempt takes and a replay loop so players can keep trying to beat their best time.
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely locally, so there are no ongoing costs.
Resources you used:
- quiz.py file (your quiz game script).
- Python 3.14 installation.
- Visual Studio Code with the Python extension.
Keep everything running
No action needed. Choose this if you plan to keep building Python projects or want to extend your quiz game further.
- Your quiz.py file stays where you saved it.
- Python and VS Code remain installed and ready for your next project.
Pause - I'll come back to this later
Close any running programs to free up system memory. Your files and installations stay intact for when you return.
- If the quiz is still running in your terminal, press Ctrl+C to stop it.
- Close the terminal window.
- Close Visual Studio Code.
Delete - I don't want to use this again
Remove all project files and optionally uninstall the tools you set up.
Delete your quiz file:
macOS
- Open Terminal and navigate to the folder where you saved quiz.py.
- Delete the file by running:
rm quiz.py
Windows
- Open PowerShell and navigate to the folder where you saved quiz.py.
- Delete the file by running:
Remove-Item quiz.py
Uninstall Python (optional):
macOS
- Open System Settings.
- Select General, then Storage.
- Find Python in the applications list and remove it. Alternatively, delete the Python framework folder by running:
sudo rm -rf /Library/Frameworks/Python.framework/Versions/3.14
Windows
- Open Settings.
- Select Apps, then Installed apps.
- Search for Python, click the three-dot menu next to it, and select Uninstall.
Uninstall Visual Studio Code (optional):
macOS
- Open Finder and go to your Applications folder.
- Drag Visual Studio Code to the Trash.
- Empty the Trash.
Windows
- Open Settings.
- Select Apps, then Installed apps.
- Search for Visual Studio Code, click the three-dot menu next to it, and select Uninstall.
That's a Wrap!
That's a Wrap!
Nice work! You just built your first Python program from scratch. Your quiz game takes questions, validates input, tracks scores, and even shuffles the order each time you play.
You've learned how to:
- Built an interactive quiz game that runs in the terminal using Python's core building blocks.
- Used lists and dictionaries to structure quiz data, and the random module to shuffle questions into a new order each round.
- Wrote reusable functions with input validation loops, conditionals for answer checking, and f-strings for formatted output.
- Added a countdown timer and replay functionality using the time module so players can challenge themselves across multiple rounds.
Ready to quiz yourself?