Advanced Quiz Application Using Python, Pandas, Matplotlib & MySQL | CBSE Class 12 IP Project

Published on October 31, 2025 by @mritxperts

Table of Contents

  1. Introduction
  2. Project Overview
  3. Prerequisites
  4. Database Design
  5. Complete Source Code
  6. Features Explained
  7. How to Run the Application
  8. Sample Output
  9. Conclusion

Introduction

Welcome to this comprehensive tutorial by Vikram Singh Rawat from Itxperts! In this guide, we’ll build an advanced Quiz Application specifically designed for CBSE Class 12 Informatics Practices (IP) students. This project covers all essential concepts including Python programming, database connectivity with MySQL, data analysis using Pandas, and data visualization with Matplotlib.

This tutorial is perfect for:

  • CBSE Class 12 IP students preparing for board practicals
  • Students working on their IP project
  • Anyone learning Python with database integration
  • Educators looking for comprehensive project examples

Project Overview

What We’ll Build

Our Advanced Quiz Application includes:

βœ… MySQL Database Integration – Store questions, users, and scores
βœ… User Authentication – Register and login functionality
βœ… Multiple Quiz Categories – Python, Database, Data Science
βœ… Score Tracking – Save and retrieve user performance
βœ… Data Analysis with Pandas – Analyze quiz statistics
βœ… Data Visualization with Matplotlib – Generate performance charts
βœ… Leaderboard System – Compare scores with other users
βœ… Admin Panel – Add new questions dynamically

Technologies Used

  • Python 3.x – Core programming language
  • MySQL – Database management
  • Pandas – Data manipulation and analysis
  • Matplotlib – Data visualization
  • mysql-connector-python – Database connectivity

Prerequisites

Software Requirements

Before starting, ensure you have:

  1. Python 3.7+ installed (Download Python)
  2. MySQL Server installed (Download MySQL)
  3. Required Python libraries

Installing Required Libraries

Open your command prompt or terminal and run:

pip install mysql-connector-python pandas matplotlib

Database Design

Step 1: Create Database and Tables

Open MySQL Command Line or MySQL Workbench and execute:

-- Create Database
CREATE DATABASE quiz_app;
USE quiz_app;

-- Users Table
CREATE TABLE users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    email VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Questions Table
CREATE TABLE questions (
    question_id INT AUTO_INCREMENT PRIMARY KEY,
    category VARCHAR(50) NOT NULL,
    question_text TEXT NOT NULL,
    option_a VARCHAR(200) NOT NULL,
    option_b VARCHAR(200) NOT NULL,
    option_c VARCHAR(200) NOT NULL,
    option_d VARCHAR(200) NOT NULL,
    correct_answer CHAR(1) NOT NULL,
    difficulty VARCHAR(20) DEFAULT 'Medium'
);

-- Scores Table
CREATE TABLE scores (
    score_id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    category VARCHAR(50) NOT NULL,
    score INT NOT NULL,
    total_questions INT NOT NULL,
    percentage DECIMAL(5,2),
    quiz_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(user_id)
);

-- Insert Sample Questions
INSERT INTO questions (category, question_text, option_a, option_b, option_c, option_d, correct_answer, difficulty) VALUES
('Python', 'What is the output of: print(type([]))?', 'list', 'dict', 'tuple', 'set', 'A', 'Easy'),
('Python', 'Which method is used to add an element at the end of a list?', 'add()', 'append()', 'insert()', 'extend()', 'B', 'Easy'),
('Python', 'What does the len() function return?', 'Size in bytes', 'Number of elements', 'Memory address', 'Data type', 'B', 'Easy'),
('Database', 'Which SQL command is used to retrieve data?', 'GET', 'SELECT', 'FETCH', 'RETRIEVE', 'B', 'Easy'),
('Database', 'What does CRUD stand for?', 'Create Read Update Delete', 'Copy Run Update Drop', 'Create Retrieve Upload Delete', 'Connect Read Use Drop', 'A', 'Medium'),
('Database', 'Which constraint ensures uniqueness?', 'PRIMARY KEY', 'FOREIGN KEY', 'CHECK', 'DEFAULT', 'A', 'Easy'),
('Data Science', 'Which library is used for data manipulation in Python?', 'NumPy', 'Pandas', 'Matplotlib', 'Seaborn', 'B', 'Easy'),
('Data Science', 'What does CSV stand for?', 'Computer Separated Values', 'Comma Separated Values', 'Cell Separated Values', 'Column Separated Values', 'B', 'Easy'),
('Data Science', 'Which chart is best for showing trends over time?', 'Pie Chart', 'Bar Chart', 'Line Chart', 'Scatter Plot', 'C', 'Medium');

Complete Source Code

Main Application Code – quiz_app.py

"""
Advanced Quiz Application
Author: Vikram Singh Rawat
Organization: Itxperts
For: CBSE Class 12 Informatics Practices
"""

import mysql.connector
from mysql.connector import Error
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import sys

class QuizDatabase:
    """Handles all database operations"""
    
    def __init__(self, host='localhost', user='root', password='', database='quiz_app'):
        """Initialize database connection"""
        try:
            self.connection = mysql.connector.connect(
                host=host,
                user=user,
                password=password,
                database=database
            )
            if self.connection.is_connected():
                print("βœ“ Connected to MySQL Database")
                self.cursor = self.connection.cursor()
        except Error as e:
            print(f"βœ— Error connecting to MySQL: {e}")
            sys.exit(1)
    
    def register_user(self, username, password, email):
        """Register a new user"""
        try:
            query = "INSERT INTO users (username, password, email) VALUES (%s, %s, %s)"
            self.cursor.execute(query, (username, password, email))
            self.connection.commit()
            return True
        except Error as e:
            print(f"Registration Error: {e}")
            return False
    
    def login_user(self, username, password):
        """Verify user credentials"""
        query = "SELECT user_id, username FROM users WHERE username=%s AND password=%s"
        self.cursor.execute(query, (username, password))
        result = self.cursor.fetchone()
        return result
    
    def get_questions_by_category(self, category):
        """Fetch questions for a specific category"""
        query = "SELECT * FROM questions WHERE category=%s ORDER BY RAND() LIMIT 5"
        self.cursor.execute(query, (category,))
        return self.cursor.fetchall()
    
    def save_score(self, user_id, category, score, total):
        """Save quiz score to database"""
        percentage = (score / total) * 100
        query = """INSERT INTO scores (user_id, category, score, total_questions, percentage) 
                   VALUES (%s, %s, %s, %s, %s)"""
        self.cursor.execute(query, (user_id, category, score, total, percentage))
        self.connection.commit()
    
    def get_user_scores(self, user_id):
        """Get all scores for a user"""
        query = """SELECT category, score, total_questions, percentage, quiz_date 
                   FROM scores WHERE user_id=%s ORDER BY quiz_date DESC"""
        self.cursor.execute(query, (user_id,))
        return self.cursor.fetchall()
    
    def get_leaderboard(self):
        """Get top 10 performers"""
        query = """SELECT u.username, s.category, s.score, s.percentage, s.quiz_date
                   FROM scores s JOIN users u ON s.user_id = u.user_id
                   ORDER BY s.percentage DESC, s.quiz_date DESC LIMIT 10"""
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def add_question(self, category, question, opt_a, opt_b, opt_c, opt_d, correct, difficulty):
        """Add new question to database"""
        query = """INSERT INTO questions (category, question_text, option_a, option_b, 
                   option_c, option_d, correct_answer, difficulty) 
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"""
        self.cursor.execute(query, (category, question, opt_a, opt_b, opt_c, opt_d, correct, difficulty))
        self.connection.commit()
    
    def close(self):
        """Close database connection"""
        if self.connection.is_connected():
            self.cursor.close()
            self.connection.close()
            print("βœ“ Database connection closed")


class QuizAnalytics:
    """Handle data analysis and visualization using Pandas and Matplotlib"""
    
    def __init__(self, db):
        self.db = db
    
    def analyze_user_performance(self, user_id):
        """Analyze and visualize user performance"""
        scores = self.db.get_user_scores(user_id)
        
        if not scores:
            print("No quiz history found!")
            return
        
        # Create DataFrame
        df = pd.DataFrame(scores, columns=['Category', 'Score', 'Total', 'Percentage', 'Date'])
        
        print("\n" + "="*70)
        print("YOUR PERFORMANCE ANALYSIS")
        print("="*70)
        print(df.to_string(index=False))
        print("="*70)
        
        # Statistics
        print(f"\nTotal Quizzes Attempted: {len(df)}")
        print(f"Average Score: {df['Percentage'].mean():.2f}%")
        print(f"Best Score: {df['Percentage'].max():.2f}%")
        print(f"Worst Score: {df['Percentage'].min():.2f}%")
        
        # Visualization
        self.plot_performance(df)
    
    def plot_performance(self, df):
        """Create performance visualization"""
        fig, axes = plt.subplots(1, 2, figsize=(14, 5))
        
        # Plot 1: Category-wise Average Scores
        category_avg = df.groupby('Category')['Percentage'].mean()
        axes[0].bar(category_avg.index, category_avg.values, color=['#FF6B6B', '#4ECDC4', '#45B7D1'])
        axes[0].set_title('Average Score by Category', fontsize=14, fontweight='bold')
        axes[0].set_xlabel('Category')
        axes[0].set_ylabel('Average Percentage')
        axes[0].set_ylim(0, 100)
        axes[0].grid(axis='y', alpha=0.3)
        
        # Plot 2: Score Trend Over Time
        axes[1].plot(range(len(df)), df['Percentage'], marker='o', color='#FF6B6B', linewidth=2)
        axes[1].set_title('Score Trend Over Time', fontsize=14, fontweight='bold')
        axes[1].set_xlabel('Quiz Number')
        axes[1].set_ylabel('Percentage')
        axes[1].set_ylim(0, 100)
        axes[1].grid(True, alpha=0.3)
        
        plt.tight_layout()
        plt.savefig('quiz_performance.png', dpi=300, bbox_inches='tight')
        print("\nβœ“ Performance chart saved as 'quiz_performance.png'")
        plt.show()
    
    def show_leaderboard(self):
        """Display leaderboard"""
        leaderboard = self.db.get_leaderboard()
        
        if not leaderboard:
            print("No scores available yet!")
            return
        
        df = pd.DataFrame(leaderboard, columns=['Username', 'Category', 'Score', 'Percentage', 'Date'])
        
        print("\n" + "="*80)
        print("πŸ† GLOBAL LEADERBOARD - TOP 10 PERFORMERS πŸ†".center(80))
        print("="*80)
        print(df.to_string(index=False))
        print("="*80)


class QuizGame:
    """Main quiz game logic"""
    
    def __init__(self, db, user_id, username):
        self.db = db
        self.user_id = user_id
        self.username = username
        self.analytics = QuizAnalytics(db)
    
    def display_menu(self):
        """Display main menu"""
        while True:
            print("\n" + "="*60)
            print(f"WELCOME, {self.username.upper()}!".center(60))
            print("="*60)
            print("1. Take Python Quiz")
            print("2. Take Database Quiz")
            print("3. Take Data Science Quiz")
            print("4. View My Performance")
            print("5. View Leaderboard")
            print("6. Add New Question (Admin)")
            print("7. Logout")
            print("="*60)
            
            choice = input("\nEnter your choice (1-7): ").strip()
            
            if choice == '1':
                self.take_quiz('Python')
            elif choice == '2':
                self.take_quiz('Database')
            elif choice == '3':
                self.take_quiz('Data Science')
            elif choice == '4':
                self.analytics.analyze_user_performance(self.user_id)
            elif choice == '5':
                self.analytics.show_leaderboard()
            elif choice == '6':
                self.add_question()
            elif choice == '7':
                print(f"\nπŸ‘‹ Goodbye, {self.username}! Thanks for playing!")
                break
            else:
                print("❌ Invalid choice! Please try again.")
    
    def take_quiz(self, category):
        """Conduct quiz for selected category"""
        questions = self.db.get_questions_by_category(category)
        
        if not questions:
            print(f"No questions available for {category}")
            return
        
        score = 0
        print(f"\n{'='*60}")
        print(f"{category.upper()} QUIZ".center(60))
        print(f"{'='*60}")
        print(f"Total Questions: {len(questions)}")
        print(f"{'='*60}\n")
        
        for i, q in enumerate(questions, 1):
            q_id, cat, text, opt_a, opt_b, opt_c, opt_d, correct, difficulty = q
            
            print(f"Q{i}. {text}")
            print(f"   A) {opt_a}")
            print(f"   B) {opt_b}")
            print(f"   C) {opt_c}")
            print(f"   D) {opt_d}")
            
            answer = input("\nYour Answer (A/B/C/D): ").strip().upper()
            
            if answer == correct:
                print("βœ“ Correct!\n")
                score += 1
            else:
                print(f"βœ— Wrong! Correct answer: {correct}\n")
        
        # Save score
        self.db.save_score(self.user_id, category, score, len(questions))
        
        percentage = (score / len(questions)) * 100
        print("="*60)
        print("QUIZ COMPLETED!".center(60))
        print("="*60)
        print(f"Score: {score}/{len(questions)}")
        print(f"Percentage: {percentage:.2f}%")
        
        if percentage >= 80:
            print("Grade: Excellent! 🌟")
        elif percentage >= 60:
            print("Grade: Good! πŸ‘")
        elif percentage >= 40:
            print("Grade: Average πŸ“š")
        else:
            print("Grade: Need Improvement πŸ’ͺ")
        print("="*60)
    
    def add_question(self):
        """Add new question to database"""
        print("\n" + "="*60)
        print("ADD NEW QUESTION".center(60))
        print("="*60)
        
        category = input("Category (Python/Database/Data Science): ").strip()
        question = input("Question: ").strip()
        opt_a = input("Option A: ").strip()
        opt_b = input("Option B: ").strip()
        opt_c = input("Option C: ").strip()
        opt_d = input("Option D: ").strip()
        correct = input("Correct Answer (A/B/C/D): ").strip().upper()
        difficulty = input("Difficulty (Easy/Medium/Hard): ").strip()
        
        self.db.add_question(category, question, opt_a, opt_b, opt_c, opt_d, correct, difficulty)
        print("βœ“ Question added successfully!")


class QuizApplication:
    """Main application class"""
    
    def __init__(self):
        print("\n" + "="*70)
        print("ADVANCED QUIZ APPLICATION".center(70))
        print("Developed by: Vikram Singh Rawat | Itxperts".center(70))
        print("For: CBSE Class 12 Informatics Practices".center(70))
        print("="*70)
        
        # Database configuration - CHANGE THESE VALUES
        self.db = QuizDatabase(
            host='localhost',
            user='root',
            password='your_password',  # Change this
            database='quiz_app'
        )
    
    def start(self):
        """Start the application"""
        while True:
            print("\n" + "="*60)
            print("MAIN MENU".center(60))
            print("="*60)
            print("1. Register New User")
            print("2. Login")
            print("3. Exit")
            print("="*60)
            
            choice = input("\nEnter your choice (1-3): ").strip()
            
            if choice == '1':
                self.register()
            elif choice == '2':
                user = self.login()
                if user:
                    game = QuizGame(self.db, user[0], user[1])
                    game.display_menu()
            elif choice == '3':
                print("\nπŸ‘‹ Thank you for using Quiz Application!")
                self.db.close()
                sys.exit(0)
            else:
                print("❌ Invalid choice! Please try again.")
    
    def register(self):
        """Register new user"""
        print("\n" + "="*60)
        print("USER REGISTRATION".center(60))
        print("="*60)
        
        username = input("Enter Username: ").strip()
        password = input("Enter Password: ").strip()
        email = input("Enter Email: ").strip()
        
        if self.db.register_user(username, password, email):
            print("βœ“ Registration successful! Please login.")
        else:
            print("βœ— Registration failed! Username may already exist.")
    
    def login(self):
        """Login user"""
        print("\n" + "="*60)
        print("USER LOGIN".center(60))
        print("="*60)
        
        username = input("Enter Username: ").strip()
        password = input("Enter Password: ").strip()
        
        user = self.db.login_user(username, password)
        
        if user:
            print(f"βœ“ Login successful! Welcome, {user[1]}!")
            return user
        else:
            print("βœ— Invalid credentials!")
            return None


# Main execution
if __name__ == "__main__":
    app = QuizApplication()
    app.start()

Features Explained

1. Database Integration

The application uses MySQL to store:

  • Users: User credentials and profile information
  • Questions: Quiz questions with multiple categories
  • Scores: User performance history

Key Learning: Understanding CRUD operations, foreign keys, and relational database design.

2. User Authentication

  • Secure registration and login system
  • Password validation
  • User session management

Key Learning: Implementing authentication logic in Python.

3. Quiz System

  • Multiple categories (Python, Database, Data Science)
  • Random question selection
  • Instant feedback on answers
  • Score calculation and grading

Key Learning: Conditional statements, loops, and function design.

4. Pandas Integration

Used for:

  • Data manipulation and analysis
  • Creating DataFrames from database records
  • Statistical calculations (mean, max, min)
  • Grouping and aggregation

Key Learning: Real-world data analysis techniques.

5. Matplotlib Visualization

Creates two types of charts:

  • Bar Chart: Category-wise average performance
  • Line Chart: Score trends over time

Key Learning: Data visualization principles and chart customization.

6. Leaderboard System

  • Global ranking of top performers
  • Displays username, category, score, and date
  • Encourages competitive learning

Key Learning: JOIN operations and advanced SQL queries.


How to Run the Application

Step 1: Setup Database

  1. Open MySQL Command Line or Workbench
  2. Copy and paste the database creation script provided above
  3. Execute all SQL commands

Step 2: Configure Database Connection

In the quiz_app.py file, update the database credentials:

self.db = QuizDatabase(
    host='localhost',
    user='root',
    password='your_mysql_password',  # Change this
    database='quiz_app'
)

Step 3: Run the Application

Open terminal/command prompt in the project folder:

python quiz_app.py

Step 4: Register and Play

  1. Choose option 1 to register
  2. Login with your credentials
  3. Select a quiz category
  4. Answer questions
  5. View your performance analytics

Sample Output

======================================================================
                    ADVANCED QUIZ APPLICATION
              Developed by: Vikram Singh Rawat | Itxperts
              For: CBSE Class 12 Informatics Practices
======================================================================
βœ“ Connected to MySQL Database

============================================================
                          MAIN MENU
============================================================
1. Register New User
2. Login
3. Exit
============================================================

Enter your choice (1-3): 2

============================================================
                        USER LOGIN
============================================================
Enter Username: john_doe
Enter Password: ****
βœ“ Login successful! Welcome, john_doe!

============================================================
                    WELCOME, JOHN_DOE!
============================================================
1. Take Python Quiz
2. Take Database Quiz
3. Take Data Science Quiz
4. View My Performance
5. View Leaderboard
6. Add New Question (Admin)
7. Logout
============================================================

Enter your choice (1-7): 1

============================================================
                        PYTHON QUIZ
============================================================
Total Questions: 5
============================================================

Q1. What is the output of: print(type([]))?
   A) list
   B) dict
   C) tuple
   D) set

Your Answer (A/B/C/D): A
βœ“ Correct!

[... more questions ...]

============================================================
                      QUIZ COMPLETED!
============================================================
Score: 4/5
Percentage: 80.00%
Grade: Excellent! 🌟
============================================================

Conclusion

Congratulations! You’ve successfully created an Advanced Quiz Application that demonstrates:

βœ… Python programming fundamentals
βœ… MySQL database integration
βœ… Pandas for data analysis
βœ… Matplotlib for data visualization
βœ… Object-oriented programming
βœ… Error handling and validation

Learning Outcomes for CBSE Class 12 IP Students

This project covers:

  • Unit 1: Python Programming (OOP, Functions, Exception Handling)
  • Unit 2: Database Concepts (SQL, CRUD Operations)
  • Unit 3: Data Handling with Pandas
  • Unit 4: Data Visualization with Matplotlib

Project Customization Ideas

  1. Add timer functionality for quizzes
  2. Implement difficulty-based scoring
  3. Add email notifications for scores
  4. Create GUI using Tkinter
  5. Add export functionality for reports
  6. Implement admin dashboard
  7. Add quiz sharing features
  8. Create mobile-responsive web interface

Additional Resources


About the Author

Vikram Singh Rawat is an experienced educator and developer at Itxperts, specializing in Python programming and database management. With years of experience in teaching CBSE Informatics Practices, Vikram creates comprehensive tutorials and projects that help students excel in their board examinations.

Contact Itxperts

For more tutorials, project ideas, and educational contents


Happy Coding! πŸš€

This tutorial is designed specifically for CBSE Class 12 Informatics Practices students. Feel free to customize and enhance this project according to your requirements.


Disclaimer: Remember to change the database credentials before running the application. Never share your actual database passwords publicly.