🧠 AI Computer Institute
Content is AI-generated for educational purposes. Verify critical information independently. A bharath.ai initiative.

CBSE Class 12 Computer Science (083) Comprehensive Guide

exam-prepGrades 129 sections

Python Object-Oriented Programming

CBSE Class 12 Core Topic: Classes, objects, inheritance, polymorphism, encapsulation.

// Class Definition
class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll

    def display(self):
        print(f"Name: {self.name}, Roll: {self.roll}")

student1 = Student("Raj", 101)
student1.display()

// Constructor (__init__)
Special method called when object created
Initialize instance variables
Can take parameters

// Instance vs Class Variables
class Employee:
    company = "TechCorp"  # Class variable (shared)

    def __init__(self, name, salary):
        self.name = name  # Instance variable
        self.salary = salary

emp1 = Employee("Priya", 50000)
emp1.name  # Access instance variable
Employee.company  # Access class variable

// Inheritance (Reuse code from parent)
class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}"

class Student(Person):  # Inherits from Person
    def __init__(self, name, roll):
        super().__init__(name)  # Call parent constructor
        self.roll = roll

s = Student("Amit", 102)
s.greet()  # Inherited method

// Polymorphism (Many forms)
Different classes, same method name

class Dog:
    def sound(self):
        return "Woof!"

class Cat:
    def sound(self):
        return "Meow!"

def make_sound(animal):
    print(animal.sound())

make_sound(Dog())  # Woof!
make_sound(Cat())  # Meow!

// Encapsulation (Hide internal details)
Use private variables with __ prefix
class Account:
    def __init__(self, balance):
        self.__balance = balance  # Private

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = Account(1000)
account.deposit(500)
balance = account.get_balance()  # Safe access

// String Methods Review
str.upper(), lower(), capitalize()
str.replace(old, new)
str.split(separator), str.join(list)
str.strip()  # Remove whitespace
str.find(substring), str.count(substring)
str.startswith(), str.endswith()

Data Structures: Stack & Queue

CBSE Class 12 includes: Implementation, operations, real-world applications.

// Stack (LIFO - Last In First Out)
Operations:
- Push: Add element to top
- Pop: Remove from top
- Peek: View top without removing
- isEmpty: Check if empty

List-based implementation:
class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.isEmpty():
            return self.items.pop()

    def peek(self):
        if not self.isEmpty():
            return self.items[-1]

    def isEmpty(self):
        return len(self.items) == 0

stack = Stack()
stack.push(10)
stack.push(20)
stack.pop()  # 20

// Stack Applications
Expression evaluation: Convert infix to postfix
Function calls: Call stack manages recursion
Undo/Redo: Store previous states
Bracket matching: [{()}]

// Queue (FIFO - First In First Out)
Operations:
- Enqueue: Add to rear
- Dequeue: Remove from front
- isEmpty, isFull

List-based implementation:
class Queue:
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.append(item)

    def dequeue(self):
        if not self.isEmpty():
            return self.items.pop(0)

    def isEmpty(self):
        return len(self.items) == 0

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.dequeue()  # 1

// Circular Queue (More efficient)
Rear pointer wraps around
Prevents wasted space
Implementation uses modulo arithmetic
Index = (front + 1) % capacity

// Deque (Double-ended queue)
Add/remove from both ends
Useful for: Sliding window, A* algorithm

// Queue Applications
Printer queue: Jobs processed FIFO
Customer service: Ticket queue
BFS algorithm: Explore level-by-level
Task scheduling: Fair time allocation

// Comparison
Stack: LIFO, push/pop ends at same place
Queue: FIFO, enqueue rear, dequeue front
Deque: Both ends accessible

SQL: Advanced Queries & Database Design

CBSE Class 12 Database: Joins, GROUP BY, aggregate functions, complex queries.

// Aggregate Functions
COUNT(*): Count rows
COUNT(column): Count non-NULL values
SUM(column): Total sum
AVG(column): Average value
MAX(column): Maximum value
MIN(column): Minimum value

SELECT COUNT(*) FROM Students;  -- How many students?
SELECT AVG(Marks) FROM Students;  -- Average marks?
SELECT MAX(Marks), MIN(Marks) FROM Students;

// GROUP BY (Aggregate by category)
SELECT Class, COUNT(*) FROM Students GROUP BY Class;
-- How many students in each class?

SELECT Department, AVG(Salary) FROM Employees
GROUP BY Department;
-- Average salary per department?

// HAVING (Filter groups)
SELECT Class, AVG(Marks) FROM Students
GROUP BY Class
HAVING AVG(Marks) > 75;
-- Classes with average > 75?

// JOIN (Combine tables)
INNER JOIN: Only matching rows
SELECT Students.Name, Marks.Score
FROM Students
INNER JOIN Marks ON Students.StudentID = Marks.StudentID;

LEFT JOIN: All from left + matching from right
SELECT Students.Name, Marks.Score
FROM Students
LEFT JOIN Marks ON Students.StudentID = Marks.StudentID;

RIGHT JOIN: All from right + matching from left
OUTER JOIN: All rows from both tables

// ORDER BY (Sort results)
SELECT * FROM Students ORDER BY Marks DESC;
SELECT * FROM Students ORDER BY Name ASC;
SELECT * FROM Students ORDER BY Marks DESC, Name ASC;

// LIMIT (Restrict rows)
SELECT * FROM Students LIMIT 5;  -- First 5
SELECT * FROM Students LIMIT 5 OFFSET 10;  -- Skip 10, take 5

// DISTINCT (Remove duplicates)
SELECT DISTINCT City FROM Students;  -- Unique cities

// WHERE vs HAVING
WHERE: Filter rows before grouping
HAVING: Filter groups after grouping

Example:
SELECT Class, AVG(Marks) FROM Students
WHERE Marks > 50  -- Include only marks > 50
GROUP BY Class
HAVING AVG(Marks) > 75  -- Show classes with avg > 75

// Subqueries (Query within query)
SELECT Name FROM Students
WHERE Marks > (SELECT AVG(Marks) FROM Students);
-- Students with above-average marks?

// ALTER TABLE
ALTER TABLE Students ADD COLUMN Address VARCHAR(100);
ALTER TABLE Students MODIFY COLUMN Name VARCHAR(100);
ALTER TABLE Students DROP COLUMN Address;

// CREATE INDEX (Faster queries)
CREATE INDEX idx_name ON Students(Name);
Queries on Name column now faster
Tradeoff: Slower inserts/updates

// Transaction (ACID properties)
BEGIN TRANSACTION;
UPDATE Account SET Balance = Balance - 100 WHERE ID = 1;
UPDATE Account SET Balance = Balance + 100 WHERE ID = 2;
COMMIT;  -- All succeed or all fail

Networking & Communication Protocols

CBSE Class 12 Networking: TCP/IP model, protocols, layers, Internet communication.

// TCP/IP Model (4 Layers)

Layer 4: Application
- HTTP, HTTPS, FTP, SMTP, POP3, SSH, Telnet
- User-facing protocols
- Examples: Web, email, file transfer

Layer 3: Transport
- TCP (Reliable, ordered, slower)
- UDP (Fast, unreliable, connectionless)
- Port numbers (80, 443, 21, 25, etc.)
- Flow control, error detection

Layer 2: Internet
- IP (IPv4, IPv6)
- Routing (paths between networks)
- Logical addressing (IP addresses)
- Packet forwarding

Layer 1: Link
- Ethernet, WiFi
- Physical transmission
- MAC addresses
- Frame structure

// TCP vs UDP
TCP:
✓ Connection-oriented (handshake)
✓ Reliable delivery
✓ In-order delivery
✓ Error checking
✓ Slower
Use: Email, web, file transfer, telnet

UDP:
✓ Connectionless
✓ Fast
✓ No error checking
✓ No guaranteed order
✓ Faster, less overhead
Use: Video streaming, VoIP, games, DNS

// Protocol Stack Example
Web browsing (HTTPS):
- Application: HTTPS
- Transport: TCP
- Internet: IP
- Link: Ethernet/WiFi

Email sending (SMTP):
- Application: SMTP
- Transport: TCP
- Internet: IP
- Link: Ethernet/WiFi

// IPv4 Addressing
Format: 4 octets (0-255 each)
192.168.1.1
Class A: 1-126 (16M hosts)
Class B: 128-191 (65K hosts)
Class C: 192-223 (254 hosts)
Loopback: 127.x.x.x

Subnet Mask: Identifies network portion
255.255.255.0 → First 3 octets are network
Network address: AND IP with mask
Broadcast: Set host bits to 1

// DNS (Domain Name System)
Resolves domain → IP address
Hierarchical: Root → TLD → Authoritative
Query process: Recursive resolver
Caching: Speeds up repeated lookups
Records: A, AAAA, MX, CNAME, TXT

// Port Numbers
Well-known ports: 0-1023
HTTP: 80, HTTPS: 443, FTP: 21
SMTP: 25, POP3: 110, SSH: 22
MySQL: 3306, PostgreSQL: 5432

// Packet Structure
IP Header: Source IP, Destination IP, TTL, Protocol
TCP/UDP Header: Source port, Destination port
Payload: Actual data
Checksum: Error detection

// Bandwidth vs Latency
Bandwidth: Data transfer rate (Mbps, Gbps)
Throughput: Actual rate achieved
Latency: Delay in transmission (ms)
Jitter: Variation in latency

Boolean Algebra & Logic Gates

CBSE Class 12 Digital Electronics: Logic, gate design, simplification, circuit optimization.

// Boolean Operations
AND (·): A·B = 1 only if both 1
OR (+): A+B = 1 if at least one 1
NOT ('): A' = opposite of A
XOR (⊕): A⊕B = 1 if different
XNOR (⊙): A⊙B = 1 if same

// De Morgan's Laws
(A·B)' = A' + B'
(A+B)' = A'·B'

Examples:
(P AND Q)' = (NOT P) OR (NOT Q)
(P OR Q)' = (NOT P) AND (NOT Q)

// Boolean Identities (Memorize!)
A + 0 = A           (OR identity)
A · 1 = A           (AND identity)
A + A' = 1          (Complement)
A · A' = 0
A + A = A           (Idempotent)
A · A = A
(A')' = A           (Double negation)
A + (B+C) = (A+B)+C (Associative)
A·(B·C) = (A·B)·C
A+(B·C) = (A+B)·(A+C)  (Distributive)
A·(B+C) = (A·B)+(A·C)

// Boolean Expression Simplification
Goal: Minimize gates, reduce complexity

Method 1: Algebraic
F = A·B' + A·B = A·(B' + B) = A·1 = A

Method 2: Karnaugh Map (K-map)
2-variable, 3-variable, 4-variable maps
Group adjacent 1s in powers of 2
Each group eliminates one variable

// Universal Gates
NAND: (A·B)' = Can build all gates
NOR: (A+B)' = Can build all gates

// Logic Circuit Minimization
7 gates needed → Simplify → 2 gates
Use Boolean algebra systematically
Verify with truth table

// Multiplexer (Data Selector)
Select one input based on control lines
2^n inputs need n select lines
Output = S'A + SB (2-to-1 mux)
Applications: Data routing, bus selection

// Decoder (Address → Lines)
n inputs, 2^n outputs
One output active at a time
Applications: Address decoding, display control

// Priority Encoder
Multiple inputs, highest priority wins
Output: Binary code of highest priority
Applications: Interrupt handling

// Comparator
Compares two binary numbers
Outputs: A>B, A=B, A

Computational Thinking & Problem Solving

CBSE Class 12 Core Concept: Algorithm design, efficiency, optimization.

// Problem Decomposition
Break complex problem into manageable parts
Example: Sorting algorithm
  - Partition: Split into smaller arrays
  - Conquer: Sort partitions
  - Combine: Merge results

// Pattern Recognition
Identify patterns in data/problems
Leverage known solutions
Example: Fibonacci pattern (f(n)=f(n-1)+f(n-2))

// Abstraction
Focus on essential features
Ignore unnecessary details
Example: Sort any list using same algorithm

// Algorithm Efficiency
Time Complexity: How runtime grows with input
Space Complexity: How memory grows with input

Big-O Notation: Worst case
  O(1): Constant (array access)
  O(log n): Binary search
  O(n): Linear search
  O(n log n): Merge sort
  O(n²): Bubble sort
  O(2^n): Exponential
  O(n!): Factorial

// Analyzing Code
for i in range(n):            -- O(n)
    for j in range(n):        -- O(n)
        operation()           -- O(1)
Total: O(n²)

for i in range(n):            -- O(n)
    binary_search(arr)        -- O(log n)
Total: O(n log n)

// Optimization Techniques
1. Memoization: Cache subproblem results
   Fibonacci: O(2^n) → O(n)

2. Greedy: Local optimal choices
   Activity selection: Always pick earliest end

3. Divide & Conquer: Split into subproblems
   Merge sort, quick sort

4. Dynamic Programming: Build solution bottom-up
   Knapsack, coin change

5. Binary Search: When data sorted
   Reduce search space by half each time

// Trade-offs
Time vs Space: Fast algorithm uses more memory
Simplicity vs Efficiency: Simple code, slower
Code length vs Performance: Optimization may complicate

// Selection Sort vs Quick Sort
Selection: O(n²) always, simple, stable
Quick: O(n log n) average, fast, in-place

// Recognizing NP Problems
NP (Nondeterministic Polynomial):
- Hard to solve, easy to verify
- No known fast algorithm
- Examples: TSP, Knapsack, Sudoku
- Use heuristics/approximation

File Handling & Exception Handling in Python

CBSE Class 12 Practical: Reading/writing files, error handling, data persistence.

// File Operations
Open modes:
'r' - Read (default)
'w' - Write (overwrite)
'a' - Append
'r+' - Read & write
'wb' - Write binary
'rb' - Read binary

// Reading Files
with open('file.txt', 'r') as f:
    content = f.read()  -- Entire file as string

with open('file.txt', 'r') as f:
    lines = f.readlines()  -- List of lines (with \n)

with open('file.txt', 'r') as f:
    for line in f:  -- Iterate lines
        print(line.strip())

// Writing Files
with open('file.txt', 'w') as f:
    f.write('Hello, World!')
    f.write('\nSecond line')

with open('file.txt', 'a') as f:
    f.write('\nAppended line')

// Appending Files
with open('file.txt', 'a') as f:
    f.write('\nNew line added')

// Working with CSV
import csv

# Read CSV
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)  -- List of values

# Read as dictionaries
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['Name'], row['Score'])

# Write CSV
with open('data.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Score'])
    writer.writerow(['Raj', 85])

// Exception Handling
try:
    num = int(input("Enter number: "))
    result = 10 / num
except ValueError:
    print("Invalid input")
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Cleanup code (always runs)")

// Specific Exceptions
ValueError: Invalid value conversion
ZeroDivisionError: Division by zero
FileNotFoundError: File doesn't exist
KeyError: Dictionary key not found
IndexError: List index out of range
AttributeError: Object attribute not found
TypeError: Wrong type for operation

// Creating Custom Exceptions
class NegativeNumberError(Exception):
    pass

def check_age(age):
    if age < 0:
        raise NegativeNumberError("Age cannot be negative")

try:
    check_age(-5)
except NegativeNumberError as e:
    print(f"Error: {e}")

// File I/O with JSON
import json

# Write JSON
data = {'name': 'Raj', 'marks': 85}
with open('data.json', 'w') as f:
    json.dump(data, f)

# Read JSON
with open('data.json', 'r') as f:
    data = json.load(f)

// Binary File Operations
# Read binary
with open('image.jpg', 'rb') as f:
    binary_data = f.read()

# Copy binary file
with open('source.jpg', 'rb') as src:
    with open('dest.jpg', 'wb') as dst:
        dst.write(src.read())

Python-MySQL Integration

CBSE Class 12 Connectivity: Connecting Python to MySQL, CRUD operations.

// Install MySQL Connector
pip install mysql-connector-python

// Establish Connection
import mysql.connector

conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='school'
)

if conn.is_connected():
    print("Connected!")

cursor = conn.cursor()

// Create Table
query = """CREATE TABLE Students (
    StudentID INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(50),
    Marks INT
)"""
cursor.execute(query)
conn.commit()

// INSERT Data
insert_query = "INSERT INTO Students (Name, Marks) VALUES (%s, %s)"
data = ('Raj', 85)
cursor.execute(insert_query, data)
conn.commit()

# Multiple inserts
data_list = [('Priya', 92), ('Amit', 78)]
cursor.executemany(insert_query, data_list)
conn.commit()

// SELECT Data
select_query = "SELECT * FROM Students"
cursor.execute(select_query)
results = cursor.fetchall()
for row in results:
    print(row)  -- Tuple: (1, 'Raj', 85)

# Fetch one
cursor.execute("SELECT * FROM Students WHERE Name='Raj'")
row = cursor.fetchone()
print(row)

// UPDATE Data
update_query = "UPDATE Students SET Marks = %s WHERE Name = %s"
cursor.execute(update_query, (95, 'Raj'))
conn.commit()
print(f"Rows updated: {cursor.rowcount}")

// DELETE Data
delete_query = "DELETE FROM Students WHERE StudentID = %s"
cursor.execute(delete_query, (1,))
conn.commit()
print(f"Rows deleted: {cursor.rowcount}")

// Error Handling
try:
    cursor.execute(query)
    conn.commit()
except mysql.connector.Error as err:
    if err.errno == 2003:
        print("Cannot connect to MySQL server")
    elif err.errno == 1045:
        print("Incorrect password")
    else:
        print(err)
    conn.rollback()
finally:
    if conn.is_connected():
        cursor.close()
        conn.close()

// Transactions
try:
    cursor.execute("UPDATE Account SET Balance = Balance - 100 WHERE ID = 1")
    cursor.execute("UPDATE Account SET Balance = Balance + 100 WHERE ID = 2")
    conn.commit()  -- Both succeed
except Exception as e:
    conn.rollback()  -- Both fail
    print(f"Error: {e}")

// Using DictCursor
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM Students")
for row in cursor:
    print(row['Name'], row['Marks'])  -- Access by column name

// Connection Pooling (Advanced)
from mysql.connector import pooling

pool = pooling.MySQLConnectionPool(
    pool_name='mypool',
    pool_size=5,
    host='localhost',
    user='root',
    password='password',
    database='school'
)

conn = pool.get_connection()

Data Management & Security Best Practices

CBSE Class 12 Exam Focus: Database security, data integrity, ethical issues.

// SQL Injection Prevention
DANGER: Concatenating user input
query = "SELECT * FROM Users WHERE username='" + user_input + "'"
If user enters: ' OR '1'='1
Result: SELECT * FROM Users WHERE username='' OR '1'='1'
All users returned!

SAFE: Parameterized queries
query = "SELECT * FROM Users WHERE username = %s"
cursor.execute(query, (user_input,))
Special characters automatically escaped

// Password Security
Never store plaintext passwords
Use hashing: bcrypt, SHA-256
Add salt (random bytes) to hash
Salted hash prevents rainbow table attacks

from bcrypt import hashpw, gensalt, checkpw
password = "mypassword"
hashed = hashpw(password.encode(), gensalt())
# Check password
checkpw("mypassword".encode(), hashed)  -- True

// Data Validation
Check user input before database
Validate type: Is it integer? String?
Validate range: Is age 0-150?
Validate format: Is email valid?

def validate_age(age):
    try:
        age = int(age)
        if 0 <= age <= 150:
            return age
        else:
            raise ValueError("Age out of range")
    except ValueError:
        return None

// Backup & Recovery
Regular backups: Daily, weekly
Multiple locations: Local + cloud
Test restores: Ensure backups work
Data loss prevention

# MySQL backup
mysqldump -u user -p database > backup.sql

# Restore
mysql -u user -p database < backup.sql

// Data Privacy
Collect minimal data needed
Clear data retention policy
GDPR compliance (right to delete)
Encryption for sensitive data

// Access Control
Principle of least privilege
Users only access needed data
Admin passwords should be complex
Regular password changes

// Data Integrity
Constraints: PRIMARY KEY, UNIQUE
Foreign keys: Maintain relationships
Triggers: Automatic data validation
Transactions: Atomic operations

// Encryption
Encrypt sensitive data at rest
Use HTTPS for transmission (TLS/SSL)
Key management: Secure key storage
Example: MySQL built-in encryption

// Audit Logging
Track who accessed/modified data
When: Timestamp all changes
What: Log actual data changes
Why: Document purpose
Review logs regularly

// Backup Strategy
Full backup: Complete database
Incremental: Only changes since last
Differential: Changes since last full
Schedule: Automated daily

// Disaster Recovery Plan
Recovery Time Objective (RTO): Max downtime
Recovery Point Objective (RPO): Max data loss
Documentation: Recovery procedures
Regular drills: Test procedures

More Cheat Sheets