Quiz Game with JSON Question Bank
IntermediateBuild an interactive quiz game with dynamic question loading
1) Project Overview
This project is a console-based Quiz Game that tests the player's general knowledge.
All questions, options, and correct answers are stored in a JSON file, making the quiz easily editable and reusable without changing the Python code.
When the player starts the quiz:
- The program loads questions from the JSON file
- Each question is displayed with multiple-choice options (A, B, C, D)
- The player answers each question
- The program calculates and displays the final score at the end
π‘ Why it's useful: This project teaches how to handle structured data using JSON β a format widely used for APIs, configuration files, and data exchange in web applications.
2) Learning Objectives
By completing this project, learners will master:
| Concept | Description |
|---|---|
| JSON Handling | Learn to read and parse data from a JSON file using Python's json module |
| Data Structures | Understand lists and dictionaries in real-world applications |
| Functions & Loops | Build modular and reusable code for structured programs |
| Input Validation | Handle user inputs and errors gracefully |
| Score Calculation | Use logic and conditionals to track correct answers |
| File-Based Data Management | Store, load, and update data using files |
3) Step-by-Step Explanation
Follow these steps to build the quiz game:
- Project Setup β Create two files in a new folder:
- quiz_game.py β main Python code
- questions.json β stores quiz data
- Create the Question Bank (questions.json) β Each question will include:
- The question text
- Four answer options
- The correct answer key (A/B/C/D)
- Load the JSON File β Use Python's built-in json module to open and read data from the file
- Display Each Question β Use a loop to display the question, show multiple-choice options, and ask the user to input an answer
- Validate Input β Ensure the user enters only A, B, C, or D
- Track the Score β Compare the user's answer to the correct answer, and update the score
- Display Final Results β After all questions are answered, show the total score, optionally calculate the percentage and feedback message
4) Complete, Well-Commented, and Verified Python Code
Save the following code as quiz_game.py:
# ------------------------------------------------------------
# π§ Quiz Game with JSON Question Bank
# Author: Your Name
# Level: Intermediate
# Verified: Python 3.8+
# ------------------------------------------------------------
import json
def load_questions(filename):
"""Load quiz questions from a JSON file."""
try:
with open(filename, "r") as file:
data = json.load(file)
return data
except FileNotFoundError:
print("β Error: Question file not found!")
return []
except json.JSONDecodeError:
print("β Error: Invalid JSON format.")
return []
def run_quiz(questions):
"""Run the quiz game using loaded questions."""
if not questions:
print("No questions to display.")
return
score = 0
total = len(questions)
print("\nπ§ Welcome to the Python Quiz Game!")
print("===================================")
print(f"Total Questions: {total}")
print("Type A, B, C, or D to answer.\n")
for index, q in enumerate(questions, start=1):
print(f"Q{index}: {q['question']}")
for key, value in q["options"].items():
print(f" {key}. {value}")
# Get user input and validate
while True:
answer = input("Your answer (A/B/C/D): ").strip().upper()
if answer in ["A", "B", "C", "D"]:
break
else:
print("β Invalid input. Please enter A, B, C, or D.")
# Check answer
if answer == q["answer"]:
print("β
Correct!\n")
score += 1
else:
print(f"β Wrong! The correct answer was: {q['answer']}\n")
# Final score
print("===================================")
print(f"π Quiz Completed!")
print(f"Your Score: {score}/{total}")
percentage = (score / total) * 100
print(f"Percentage: {percentage:.2f}%")
if percentage == 100:
print("π Excellent! Perfect Score!")
elif percentage >= 70:
print("π Great job! You know your stuff.")
elif percentage >= 50:
print("π Not bad. Keep practicing!")
else:
print("π‘ You can do better next time!")
print("===================================")
def main():
"""Main function to control the game."""
filename = "questions.json"
questions = load_questions(filename)
run_quiz(questions)
# Run program
if __name__ == "__main__":
main()β’ Runs perfectly in Python 3.8+
β’ Works with any JSON file of similar structure
β’ Handles invalid inputs safely
β’ Graceful error messages for missing/invalid JSON
5) Output Example (Sample Run)
===================================
Total Questions: 3
Type A, B, C, or D to answer.
Q1: What is the capital of France?
A. Berlin
B. Madrid
C. Paris
D. Lisbon
Your answer (A/B/C/D): C
β Correct!
Q2: Which planet is known as the Red Planet?
A. Earth
B. Mars
C. Jupiter
D. Venus
Your answer (A/B/C/D): A
β Wrong! The correct answer was: B
Q3: Who wrote 'Romeo and Juliet'?
A. Charles Dickens
B. Mark Twain
C. William Shakespeare
D. Jane Austen
Your answer (A/B/C/D): C
β Correct!
===================================
π Quiz Completed!
Your Score: 2/3
Percentage: 66.67%
π Not bad. Keep practicing!
===================================
6) Extension Challenge
π― Ideas to make it more advanced
Goal: Enhance your quiz game with these features:
- Randomize Questions: Use the random module to shuffle the questions each time
- Add Categories or Difficulty Levels: Let users choose from "Science", "Math", or "History"
- Timer Mode: Add a countdown timer using the time module to limit answer time
- GUI Version with Tkinter: Build a window-based quiz game where users click buttons for answers
- Score Saving System: Save player scores to a separate JSON file for future reference
7) Summary
π You just built a Python Quiz Game that:
- Loads data dynamically from a JSON file
- Tests knowledge with multiple-choice questions
- Uses loops, conditionals, and file handling
- Provides real-time feedback and scoring
This project strengthens your foundation in:
- Data handling (JSON)
- Interactive programming
- Error handling and validation
π¬ "A quiz that teaches you β not just Python, but how to think like a developer!"