πŸŽ‰ Welcome to PyVerse! Start Learning Today

Quiz Game with JSON Question Bank

Intermediate

Build 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:

ConceptDescription
JSON HandlingLearn to read and parse data from a JSON file using Python's json module
Data StructuresUnderstand lists and dictionaries in real-world applications
Functions & LoopsBuild modular and reusable code for structured programs
Input ValidationHandle user inputs and errors gracefully
Score CalculationUse logic and conditionals to track correct answers
File-Based Data ManagementStore, load, and update data using files

3) Step-by-Step Explanation

Follow these steps to build the quiz game:

  1. Project Setup β€“ Create two files in a new folder:
    • quiz_game.py – main Python code
    • questions.json – stores quiz data
  2. Create the Question Bank (questions.json) β€“ Each question will include:
    • The question text
    • Four answer options
    • The correct answer key (A/B/C/D)
  3. Load the JSON File β€“ Use Python's built-in json module to open and read data from the file
  4. Display Each Question β€“ Use a loop to display the question, show multiple-choice options, and ask the user to input an answer
  5. Validate Input β€“ Ensure the user enters only A, B, C, or D
  6. Track the Score β€“ Compare the user's answer to the correct answer, and update the score
  7. 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()
βœ… Verified and Tested:
β€’ 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)

🧠 Welcome to the Python Quiz Game!
===================================
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!"