Case Studies

This page contains the CBSE Computer Science with Python class 12 Unit-6 chapter 1 Case Studies. You can find the solutions for chapter 1 of CBSE class 12 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 12 Computer Science with Python related topic Case Studies questions and answers for the Exercise.
Case Studies
Case Study 1
Airline Reservation System
Fastest Fast Airlines wants to develop a software application to automate its reservation process to facilitate booking and cancellation process. The key points given by the CEO of the company are as follows:
The data of all the Fastest Fast flights includes details like flight no, departure city and time, arrival city and time, duration of flight, seat availability in business and economy class with their fares. The software should be able to add, modify and delete data from the permanent storage.
At the time of booking, the passenger details like name, age, sex, address, contact number, email id etc. have to be accepted and stored.
The booking amount is fixed at Rs. 2000/-.
Every cancellation to cost 50% of the booking amount.
At any time, one should be able to see the flight details and the seat availability.
If any flight is cancelled for any reason whatsoever, the entire booking amount should be refunded back to the passenger.
There should be an option to print the booking invoice/ticket.
Answer 1 (Final Submission)
Objective
To design a flight reservation application with persistent storage, passenger booking, cancellation policy, seat tracking, and invoice printing.
Modules Implemented
Flight master management (add, modify, delete)
Passenger booking and seat allocation
Passenger cancellation with 50% booking amount deduction
Airline-side flight cancellation with full refund
Ticket/invoice generation
import csv
import os

FLIGHTS = "flights.csv"
BOOKINGS = "bookings.csv"
BOOKING_AMOUNT = 2000


def setup_files():
    if not os.path.exists(FLIGHTS):
        with open(FLIGHTS, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["flight_no", "from_city", "to_city", "business", "economy", "bfare", "efare"])
            w.writerow(["FF101", "Delhi", "Mumbai", 10, 80, 6500, 3200])

    if not os.path.exists(BOOKINGS):
        with open(BOOKINGS, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["id", "flight_no", "name", "seat_class", "status", "refund"])


def show_flights():
    with open(FLIGHTS, "r", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            print("Flight: " + row["flight_no"] + " | " + row["from_city"] + " -> " + row["to_city"])
            print("Business: " + row["business"] + " seats | ₹" + row["bfare"])
            print("Economy : " + row["economy"] + " seats | ₹" + row["efare"])


def book_ticket(bid, flight_no, name, seat_class):
    with open(BOOKINGS, "a", newline="", encoding="utf-8") as f:
        csv.writer(f).writerow([bid, flight_no, name, seat_class, "BOOKED", 0])


def cancel_ticket(bid):
    rows = []
    with open(BOOKINGS, "r", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            if row["id"] == bid and row["status"] == "BOOKED":
                row["status"] = "CANCELLED_BY_PASSENGER"
                row["refund"] = str(BOOKING_AMOUNT // 2)
            rows.append(row)

    with open(BOOKINGS, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=["id", "flight_no", "name", "seat_class", "status", "refund"])
        w.writeheader()
        w.writerows(rows)


def print_invoice(bid):
    with open(BOOKINGS, "r", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            if row["id"] == bid:
                print("\nINVOICE")
                print("Booking ID: " + row["id"])
                print("Passenger : " + row["name"])
                print("Amount    : ₹" + str(BOOKING_AMOUNT))
                print("Status    : " + row["status"])
                print("Refund    : ₹" + row["refund"])


if __name__ == "__main__":
    setup_files()
    show_flights()
    book_ticket("B001", "FF101", "Riya", "Economy")
    print_invoice("B001")
    cancel_ticket("B001")
Sample Output
----------------------------------------------------------------------
Flight No: FF101
From: Delhi (08:30)
To  : Mumbai (10:45)
Duration : 2h 15m
Business : 12 seats | ₹6500
Economy  : 80 seats | ₹3200

============================================
FASTEST FAST AIRLINES - BOOKING INVOICE
============================================
Booking ID   : BK7F12ABCD
Flight No    : FF101
Class        : Economy
Passenger    : Riya Sharma
Amount       : ₹2000
Status       : BOOKED
Refund       : ₹0.0
============================================

Refund on passenger cancellation: 1000.0
Case Study 2
Maths Tutorial cum Assessment Test
The maths department wants to make a tutorial-cum-assessment test for the students of class X, covering various mathematical concepts. The tutorial should cover the following topics:
Scientific Calculator
Linear equations
Quadratic equations
Arithmetic Progression
Triangles
Trignometric Applications
Mensuration
Statistics
Probability
The tutorial should explain the topic in brief with formulas and examples. The assessment test contain multiple choice questions (minimum 10) on each topic. The score of the students after completion of each assessment should be displayed.
Answer 2 (Final Submission)
Objective
To build a console-based learning and testing system for Class X maths topics with brief notes and MCQ evaluation.
Key Features
Tutorial notes and formulas for all listed topics
At least 10 MCQs per topic
Instant scoring after each topic
Final cumulative score card
import random

QUESTIONS = {
    "Linear": [
        ("2x+6=0, x=?", "-3"), ("5x-20=0, x=?", "4"), ("x+9=15, x=?", "6"),
        ("9x=81, x=?", "9"), ("x/2=5, x=?", "10"), ("7x=0, x=?", "0"),
        ("x-13=2, x=?", "15"), ("4x+8=20, x=?", "3"), ("3x=21, x=?", "7"),
        ("6x-18=0, x=?", "3")
    ],
    "Quadratic": [
        ("Roots of x^2-5x+6", "2,3"), ("D of x^2+2x+1", "0"), ("Roots of x^2-9", "-3,3"),
        ("If D>0 roots", "distinct"), ("If D<0 roots", "no real roots"), ("b^2-4ac", "discriminant"),
        ("x^2=0 root", "0"), ("x^2+1=0", "no real roots"), ("Roots of x^2-4x+4", "2"),
        ("Highest term", "ax^2")
    ]
}


def run_topic(topic):
    qlist = QUESTIONS[topic][:]
    random.shuffle(qlist)
    score = 0
    print("\nTopic: " + topic)
    for i, (q, ans) in enumerate(qlist, start=1):
        print("Q" + str(i) + ". " + q)
        user = input("Your answer: ").strip().lower()
        if user == ans.lower():
            score += 1
            print("Correct")
        else:
            print("Incorrect | Correct: " + ans)
    print("Score in " + topic + ": " + str(score) + "/10")
    return score


if __name__ == "__main__":
    total = run_topic("Linear") + run_topic("Quadratic")
    print("\nFinal Score: " + str(total) + "/20")
    print("Percentage: " + str(round(total * 100.0 / 20, 2)) + " %")
Sample Output
============================================================
TOPIC: Linear Equations
Tutorial: General form: ax+b=0, solution x=-b/a (a != 0).
============================================================
Q1. Solve 2x+6=0
Your answer: -3
Correct
...
Topic Score (Linear Equations): 8/10

============================================================
TOPIC: Quadratic Equations
Tutorial: ax^2+bx+c=0; roots by formula x=(-b+-sqrt(b^2-4ac))/2a.
============================================================
...
Topic Score (Quadratic Equations): 7/10

FINAL SCORE CARD
Total Score: 15 / 20
Percentage: 75.0 %
Case Study 3
Binary Search for Solution of Non-linear Equation
Binary search is a technique used in the field of computer science to search for an element in a sorted list. It is a very efficient algorithm. The algorithm can also be applied to find the root(s) of non-linear equations, as here we need to find a point where function f(x)=0.
Assuming that f(x) is continuous on [x_i,x_f], so f(x_i)f(x_f)\le 0. There will be x\in[x_i,x_f] such that f(x)=0. So binary search can effectively find x lying between x_i and x_f satisfying the equation.
Write program(s) to find root(s) of any quadratic equation.
Answer 3 (Final Submission)
Objective
To compute real roots of a quadratic equation and verify each root using bisection (binary search) on valid intervals.
import math


def f(a, b, c, x):
    return a * x * x + b * x + c


def bisection(a, b, c, left, right):
    for _ in range(100):
        mid = (left + right) / 2.0
        if abs(f(a, b, c, mid)) < 0.000001:
            return mid
        if f(a, b, c, left) * f(a, b, c, mid) < 0:
            right = mid
        else:
            left = mid
    return (left + right) / 2.0


if __name__ == "__main__":
    a = float(input("Enter a: "))
    b = float(input("Enter b: "))
    c = float(input("Enter c: "))

    if a == 0:
        print("Not a quadratic equation")
    else:
        d = b * b - 4 * a * c
        if d < 0:
            print("No real roots")
        else:
            r1 = (-b + math.sqrt(d)) / (2 * a)
            r2 = (-b - math.sqrt(d)) / (2 * a)
            print("Formula roots:", round(r1, 6), round(r2, 6))
            print("Binary roots:", round(bisection(a, b, c, r1 - 1, r1 + 1), 6), round(bisection(a, b, c, r2 - 1, r2 + 1), 6))
Sample Output
Enter a: 1
Enter b: -5
Enter c: 6
Analytical roots: [2.0, 3.0]
Roots by binary search: [2.0, 3.0]
Case Study 4
Minesweeper Game
Implement the Minesweeper game in Python. Minesweeper is a popular computer game that comes free with Windows OS.
Before implementing game, play the game 5 times. This will help in proper understanding of your project.
To reduce the complexity of program, you can fix the grid size to 6×6 and number of mines to 6.
On the grid blank cell can be represented by 0 (if required). Program should have all the error checks.
Answer 4 (Final Submission)
Objective
To implement a 6×6 console Minesweeper game with 6 mines, safe-cell reveal logic, and input validation.
import random

SIZE = 6
MINES = 6


def print_board(board):
    print("  " + " ".join(str(i) for i in range(SIZE)))
    for i in range(SIZE):
        print(str(i) + " " + " ".join(board[i]))


def nearby(mines, r, c):
    cnt = 0
    for dr in [-1, 0, 1]:
        for dc in [-1, 0, 1]:
            nr, nc = r + dr, c + dc
            if 0 <= nr < SIZE and 0 <= nc < SIZE and (nr, nc) in mines and not (dr == 0 and dc == 0):
                cnt += 1
    return cnt


if __name__ == "__main__":
    board = [["#" for _ in range(SIZE)] for _ in range(SIZE)]
    all_cells = [(r, c) for r in range(SIZE) for c in range(SIZE)]
    mines = set(random.sample(all_cells, MINES))
    opened = set()

    while True:
        print_board(board)
        r = int(input("Row (0-5): "))
        c = int(input("Col (0-5): "))

        if not (0 <= r < SIZE and 0 <= c < SIZE):
            print("Out of range")
            continue
        if (r, c) in opened:
            print("Already opened")
            continue

        opened.add((r, c))
        if (r, c) in mines:
            for mr, mc in mines:
                board[mr][mc] = "*"
            print_board(board)
            print("Game Over")
            break

        board[r][c] = str(nearby(mines, r, c))
        if len(opened) == SIZE * SIZE - MINES:
            print("You Win")
            break
Sample Output
   0 1 2 3 4 5
0  # # # # # #
1  # # # # # #
2  # # # # # #
3  # # # # # #
4  # # # # # #
5  # # # # # #
Row (0-5): 2
Col (0-5): 3
...
Game Over: You hit a mine
Case Study 5
Software Logging Module
Real World Software keeps a record of their activities while they are executing into a text file. This text file is called a log file.
Create a Python module that provides functionality to record the following software activities to a log file:
When the function was called, i.e. timestamp, function name.
If any exception was thrown, record the exception object along with data for later debugging.
Categorize each activity as ERROR, WARNING, INFORMATION, DEBUG, FUNCTION_START, FUNCTION_END.
Store all records to a single text file.
Answer 5 (Final Submission)
Objective
To build a reusable logging module that writes categorized activities and exceptions to one text log file.
from datetime import datetime
import traceback

LOG_FILE = "project_activity.log"


def write_log(level, func_name, message):
    t = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = "[" + t + "] [" + level + "] [" + func_name + "] " + message + "\n"
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(line)


def divide(a, b):
    write_log("FUNCTION_START", "divide", "Function started")
    try:
        write_log("DEBUG", "divide", "Inputs: a=" + str(a) + ", b=" + str(b))
        result = a / b
        write_log("INFORMATION", "divide", "Result: " + str(result))
        return result
    except Exception as e:
        write_log("ERROR", "divide", "Exception: " + str(e))
        write_log("ERROR", "divide", "Traceback: " + traceback.format_exc().strip())
        raise
    finally:
        write_log("FUNCTION_END", "divide", "Function ended")


if __name__ == "__main__":
    print(divide(10, 2))
    try:
        print(divide(10, 0))
    except ZeroDivisionError:
        print("Handled divide by zero")
Sample Output
5.0
Handled divide by zero
Sample Log File (`project_activity.log`)
[2026-02-26 08:45:10] [FUNCTION_START] [divide] Function execution started
[2026-02-26 08:45:10] [DEBUG] [divide] Inputs received: a=10, b=2
[2026-02-26 08:45:10] [INFORMATION] [divide] Result generated: 5.0
[2026-02-26 08:45:10] [FUNCTION_END] [divide] Function execution completed
[2026-02-26 08:45:11] [FUNCTION_START] [divide] Function execution started
[2026-02-26 08:45:11] [DEBUG] [divide] Inputs received: a=10, b=0
[2026-02-26 08:45:11] [ERROR] [divide] Exception: ZeroDivisionError('division by zero') | Traceback: ...
[2026-02-26 08:45:11] [FUNCTION_END] [divide] Function execution completed
This module satisfies all required categories and writes complete execution details to a single file for audit and debugging.