CBSE Class 12 - Complete Syllabus (Python & MySQL)¶
Board: Central Board of Secondary Education (CBSE) Subject: Computer Science (Code 083) Duration: 11 Months (May - March) Weekly Hours: 3 hours Total Marks: 100 (Theory 70 + Practical 30)
Course Overview ๐¶
The CBSE Class 12 Computer Science course focuses on Python programming, data structures, database management with MySQL, and computer networks. This curriculum emphasizes computational thinking and practical problem-solving skills.
Key Focus Areas: - Advanced Python programming - File handling (Text, Binary, CSV) - Data Structures (Stacks, Queues) - SQL database management - Python-MySQL integration - Computer Networks
Unit I: Computational Thinking and Programming โ 2 ๐ป¶
Marks Weightage: 40 marks Focus: Advanced Python programming with practical applications
1. Revision of Python (Class XI Topics)¶
Quick Recap: - Data types (int, float, string, boolean) - Operators and expressions - Control flow (if-else, loops) - Lists, tuples, dictionaries - String operations - Basic input/output
Why Revise?: Class 12 builds heavily on Class 11 concepts. Strong foundations are essential.
2. Functions in Detail¶
Learning Objectives: - Master function creation and usage - Understand parameter passing mechanisms - Work with return values and scope
Topics Covered:
Types of Functions:
- Built-in functions: len(), max(), min(), sum(), abs(), round()
- User-defined functions: Creating custom functions
Function Syntax:
def function_name(parameters):
"""
Docstring: Function description
"""
# Function body
return result
Parameters and Arguments:
- Positional arguments: Order matters
- Keyword arguments: Using parameter names
- Default parameters: Default values
- Variable-length arguments: *args, **kwargs
Example:
def calculate_area(length, width=10):
"""Calculate area of rectangle"""
area = length * width
return area
# Calls
print(calculate_area(5, 8)) # 40
print(calculate_area(5)) # 50 (uses default width)
Variable Scope:
- Local variables: Inside function
- Global variables: Outside function
- global keyword: Modify global variables
Flow of Execution: 1. Function is defined 2. Function is called 3. Control jumps to function 4. Function executes 5. Returns to caller
Practice Programs: 1. Function to check if number is prime 2. Function to calculate factorial 3. Function to find largest of three numbers 4. Function with default parameters 5. Function using global variables
3. Exception Handling¶
Learning Objectives: - Handle runtime errors gracefully - Use try-except-finally blocks - Understand different exception types
Topics Covered:
What are Exceptions?: Errors that occur during program execution (runtime errors).
Common Exceptions:
- ZeroDivisionError: Division by zero
- ValueError: Invalid value
- TypeError: Wrong type
- FileNotFoundError: File doesn't exist
- IndexError: Invalid index
- KeyError: Invalid dictionary key
Exception Handling Syntax:
try:
# Code that might raise exception
result = 10 / 0
except ZeroDivisionError:
# Handle specific exception
print("Cannot divide by zero")
except Exception as e:
# Handle any other exception
print(f"Error: {e}")
finally:
# Always executes (optional)
print("Cleanup code")
Raising Exceptions:
Practice Programs: 1. Handle division by zero 2. Validate user input with exception handling 3. File operation with exception handling 4. Custom exception for invalid marks
4. Introduction to Files¶
Learning Objectives: - Understand file types - Work with file paths - Prepare for file operations
File Types:
- Text Files (.txt, .csv, .log)
- Human-readable
- Plain text content
-
Can be opened with text editor
-
Binary Files (.dat, .bin, .pkl)
- Machine-readable
- Compact storage
-
Requires special libraries
-
CSV Files (.csv)
- Comma-Separated Values
- Tabular data
- Easy to import/export
File Paths:
- Absolute path: /home/user/Documents/file.txt
- Relative path: data/file.txt
5. Text File Operations¶
Learning Objectives: - Open, read, write, and close text files - Use different file modes - Manipulate file content
File Modes:
| Mode | Description | Creates if Not Exists |
|---|---|---|
'r' |
Read only | No (Error if missing) |
'w' |
Write only | Yes (Overwrites) |
'a' |
Append | Yes (Adds to end) |
'r+' |
Read and write | No |
'w+' |
Write and read | Yes (Overwrites) |
'a+' |
Append and read | Yes |
Opening and Closing Files:
# Method 1: Manual close
file = open("data.txt", "r")
content = file.read()
file.close()
# Method 2: with statement (recommended)
with open("data.txt", "r") as file:
content = file.read()
# File automatically closed
Reading Methods:
# Read entire file
content = file.read()
# Read one line
line = file.readline()
# Read all lines as list
lines = file.readlines()
# Read line by line (efficient)
for line in file:
print(line)
Writing Methods:
# Write string
file.write("Hello, World!\n")
# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)
Common File Operations:
-
Count Lines in File:
-
Count Words in File:
-
Count Vowels in File:
Practice Programs: 1. Read a file and display its contents 2. Count lines, words, and characters in a file 3. Copy content from one file to another 4. Search for a word in a file 5. Count frequency of each word in a file
6. Binary File Operations¶
Learning Objectives: - Work with binary files using pickle module - Serialize and deserialize Python objects - Store complex data structures
Topics Covered:
The pickle Module:
import pickle
# Writing to binary file (serialization)
data = {'name': 'Alice', 'age': 20, 'marks': [85, 90, 88]}
with open("data.dat", "wb") as file:
pickle.dump(data, file)
# Reading from binary file (deserialization)
with open("data.dat", "rb") as file:
data = pickle.load(file)
print(data)
dump() vs load():
- pickle.dump(object, file): Write object to binary file
- pickle.load(file): Read object from binary file
Working with Multiple Records:
# Writing multiple records
students = [
{'name': 'Alice', 'marks': 85},
{'name': 'Bob', 'marks': 90},
{'name': 'Charlie', 'marks': 78}
]
with open("students.dat", "wb") as file:
for student in students:
pickle.dump(student, file)
# Reading multiple records
students = []
with open("students.dat", "rb") as file:
try:
while True:
student = pickle.load(file)
students.append(student)
except EOFError:
pass # End of file reached
Practice Programs: 1. Store student records (name, roll no, marks) in binary file 2. Search for a student by roll number 3. Update marks of a student 4. Delete a student record 5. Display all records from binary file
7. CSV File Operations¶
Learning Objectives: - Work with CSV files using csv module - Read and write tabular data - Use csv.reader and csv.writer
Topics Covered:
What is CSV?: Comma-Separated Values format for storing tabular data.
Example CSV:
Reading CSV Files:
import csv
# Using csv.reader
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row) # row is a list
# Using csv.DictReader (with headers)
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'])
Writing CSV Files:
import csv
# Using csv.writer
data = [
['Name', 'Age', 'City'],
['Alice', 20, 'Mumbai'],
['Bob', 22, 'Delhi']
]
with open("output.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
# Using csv.DictWriter
students = [
{'Name': 'Alice', 'Age': 20, 'City': 'Mumbai'},
{'Name': 'Bob', 'Age': 22, 'City': 'Delhi'}
]
with open("output.csv", "w", newline='') as file:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(students)
Practice Programs: 1. Read CSV file and display all records 2. Add a new record to CSV file 3. Search for a record in CSV 4. Calculate average of a numeric column 5. Sort CSV records by a column
8. Data Structures - Stacks¶
Learning Objectives: - Understand stack concept (LIFO) - Implement stack using Python list - Perform stack operations
Topics Covered:
Stack Concept: - LIFO: Last In, First Out - Real-world example: Stack of plates
Stack Operations: 1. Push: Add element to top 2. Pop: Remove element from top 3. Peek/Top: View top element without removing 4. isEmpty: Check if stack is empty 5. Size: Get number of elements
Implementation Using List:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
"""Add item to top of stack"""
self.items.append(item)
def pop(self):
"""Remove and return top item"""
if not self.is_empty():
return self.items.pop()
else:
return "Stack is empty"
def peek(self):
"""Return top item without removing"""
if not self.is_empty():
return self.items[-1]
else:
return "Stack is empty"
def is_empty(self):
"""Check if stack is empty"""
return len(self.items) == 0
def size(self):
"""Return number of items"""
return len(self.items)
def display(self):
"""Display all items"""
print("Stack:", self.items)
# Usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)
s.display() # [10, 20, 30]
print(s.pop()) # 30
print(s.peek()) # 20
Stack Applications: - Function call management - Undo/Redo functionality - Expression evaluation - Backtracking algorithms - Browser history
Practice Programs: 1. Implement stack with all operations 2. Reverse a string using stack 3. Check balanced parentheses using stack 4. Convert decimal to binary using stack
9. Data Structures - Queues¶
Learning Objectives: - Understand queue concept (FIFO) - Implement queue using Python list - Perform queue operations
Topics Covered:
Queue Concept: - FIFO: First In, First Out - Real-world example: Line at ticket counter
Queue Operations: 1. Enqueue: Add element to rear 2. Dequeue: Remove element from front 3. Front: View front element 4. isEmpty: Check if queue is empty 5. Size: Get number of elements
Implementation Using List:
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
"""Add item to rear"""
self.items.append(item)
def dequeue(self):
"""Remove and return front item"""
if not self.is_empty():
return self.items.pop(0)
else:
return "Queue is empty"
def front(self):
"""Return front item without removing"""
if not self.is_empty():
return self.items[0]
else:
return "Queue is empty"
def is_empty(self):
"""Check if queue is empty"""
return len(self.items) == 0
def size(self):
"""Return number of items"""
return len(self.items)
def display(self):
"""Display all items"""
print("Queue:", self.items)
# Usage
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.display() # [10, 20, 30]
print(q.dequeue()) # 10
print(q.front()) # 20
Queue Applications: - Print job scheduling - CPU task scheduling - Breadth-first search - Network packet handling
Practice Programs: 1. Implement queue with all operations 2. Simulate ticket counter queue 3. Implement circular queue
Unit II: Computer Networks ๐¶
Marks Weightage: 10 marks Focus: Understanding network fundamentals and technologies
1. Evolution of Networking¶
Topics Covered: - ARPANET: First packet-switching network (1969) - Internet: Global network of networks - Timeline: 1960s โ 2020s - Key milestones: Email, WWW, Social Media, Cloud
2. Data Communication Terminologies¶
Key Concepts: - Sender: Transmits data - Receiver: Receives data - Message: Data being transmitted - Medium: Path for transmission - Protocol: Rules for communication
Bandwidth: Data transfer capacity (bps, Kbps, Mbps, Gbps)
3. Transmission Media¶
Wired Media: 1. Twisted Pair Cable - Telephone lines - Ethernet cables (Cat5, Cat6) - Cheap, easy to install
- Co-axial Cable
- Cable TV
- Higher bandwidth than twisted pair
-
Less interference
-
Fiber-Optic Cable
- Light signals
- Very high speed
- Expensive, long distance
Wireless Media: 1. Radio Waves: WiFi, Bluetooth 2. Microwaves: Satellite communication 3. Infrared: Remote controls
4. Network Devices¶
Common Devices: - Modem: Converts digital โ analog - Hub: Broadcasts to all devices - Switch: Sends to specific device - Router: Connects different networks - Gateway: Protocol converter - Repeater: Amplifies signal
5. Network Types and Topologies¶
Network Types: - PAN (Personal Area Network): Bluetooth, 10m - LAN (Local Area Network): Office, school, 1km - MAN (Metropolitan Area Network): City, 10km - WAN (Wide Area Network): Country, unlimited
Network Topologies: - Bus: Single cable, all devices connected - Star: Central hub, all devices connect to hub - Ring: Circular connection - Mesh: Every device connected to every other - Tree: Hierarchical structure
6. Network Protocols¶
Common Protocols: - HTTP: Web page transfer (port 80) - HTTPS: Secure HTTP (port 443) - FTP: File transfer (port 21) - SMTP: Send email (port 25) - POP3: Receive email (port 110) - TCP/IP: Internet protocol suite - DNS: Domain name to IP address
TCP vs UDP: - TCP: Reliable, connection-oriented - UDP: Fast, connectionless
7. Web Services¶
Topics Covered: - WWW (World Wide Web): Information system - HTML: Markup language for web pages - XML: Data storage and transfer - Domain Names: www.example.com - IP Address: 192.168.1.1 - Web Hosting: Server storage for websites
Unit III: Database Management ๐¶
Marks Weightage: 20 marks Focus: SQL database operations and Python-SQL integration
1. Database Concepts¶
What is a Database?: Organized collection of data stored electronically.
DBMS vs File System: | Aspect | File System | DBMS | |--------|-------------|------| | Data redundancy | High | Low | | Data consistency | Difficult | Easy | | Data security | Limited | High | | Concurrent access | No | Yes |
2. Relational Data Model¶
Key Concepts: - Relation/Table: Collection of rows and columns - Tuple/Row: Single record - Attribute/Column: Data field - Domain: Set of allowed values - Degree: Number of columns - Cardinality: Number of rows
Keys: - Primary Key: Unique identifier (cannot be NULL) - Candidate Key: Can be primary key - Alternate Key: Candidate key not chosen as primary - Foreign Key: References primary key of another table
3. Structured Query Language (SQL)¶
SQL Categories: 1. DDL (Data Definition Language): CREATE, ALTER, DROP 2. DML (Data Manipulation Language): INSERT, UPDATE, DELETE 3. DQL (Data Query Language): SELECT
Data Types: - INT: Integer numbers - FLOAT/DOUBLE: Decimal numbers - CHAR(n): Fixed-length string - VARCHAR(n): Variable-length string - DATE: Date (YYYY-MM-DD) - BOOLEAN: True/False
Constraints: - PRIMARY KEY: Unique, not null - FOREIGN KEY: Reference another table - NOT NULL: Cannot be null - UNIQUE: All values must be unique - DEFAULT: Default value - CHECK: Condition validation
4. SQL Commands¶
CREATE TABLE:
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT CHECK (age >= 15),
marks FLOAT DEFAULT 0.0,
city VARCHAR(30)
);
INSERT:
INSERT INTO students VALUES (1, 'Alice', 16, 85.5, 'Mumbai');
INSERT INTO students (roll_no, name, age) VALUES (2, 'Bob', 17);
SELECT:
-- Select all columns
SELECT * FROM students;
-- Select specific columns
SELECT name, marks FROM students;
-- WHERE clause
SELECT * FROM students WHERE marks > 80;
-- ORDER BY
SELECT * FROM students ORDER BY marks DESC;
-- LIMIT
SELECT * FROM students LIMIT 5;
UPDATE:
UPDATE students SET marks = 90 WHERE roll_no = 1;
UPDATE students SET city = 'Delhi' WHERE city IS NULL;
DELETE:
ALTER TABLE:
ALTER TABLE students ADD email VARCHAR(50);
ALTER TABLE students DROP COLUMN email;
ALTER TABLE students MODIFY COLUMN name VARCHAR(100);
DROP TABLE:
5. Aggregate Functions¶
Functions:
-- COUNT
SELECT COUNT(*) FROM students;
SELECT COUNT(DISTINCT city) FROM students;
-- SUM
SELECT SUM(marks) FROM students;
-- AVG
SELECT AVG(marks) FROM students;
-- MAX, MIN
SELECT MAX(marks), MIN(marks) FROM students;
6. GROUP BY and HAVING¶
-- GROUP BY
SELECT city, COUNT(*) FROM students GROUP BY city;
SELECT city, AVG(marks) FROM students GROUP BY city;
-- HAVING (filter groups)
SELECT city, AVG(marks) FROM students
GROUP BY city
HAVING AVG(marks) > 75;
7. Python-MySQL Integration¶
Steps:
1. Install MySQL Connector: pip install mysql-connector-python
2. Import module
3. Connect to database
4. Create cursor
5. Execute SQL
6. Commit changes
7. Close connection
Complete Example:
import mysql.connector
# 1. Connect to database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school"
)
# 2. Create cursor
cursor = mydb.cursor()
# 3. Execute SQL - CREATE TABLE
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
marks FLOAT
)
""")
# 4. INSERT data
sql = "INSERT INTO students VALUES (%s, %s, %s)"
values = (1, "Alice", 85.5)
cursor.execute(sql, values)
mydb.commit() # Save changes
# 5. SELECT data
cursor.execute("SELECT * FROM students")
results = cursor.fetchall() # Get all rows
for row in results:
print(row)
# 6. UPDATE data
cursor.execute("UPDATE students SET marks = 90 WHERE roll_no = 1")
mydb.commit()
# 7. DELETE data
cursor.execute("DELETE FROM students WHERE marks < 40")
mydb.commit()
# 8. Close connection
cursor.close()
mydb.close()
Fetch Methods:
- fetchone(): Fetch one row
- fetchall(): Fetch all rows
- fetchmany(n): Fetch n rows
Practical Syllabus ๐ ๏ธ¶
Total Practical Marks: 30
Components: 1. Lab Test (10 marks): - Python programming (6-7 marks) - SQL queries (3-4 marks)
- Project Work (10 marks):
-
Python project with file handling or database
-
Viva Voce (5 marks):
-
Oral questions on concepts
-
Practical File (5 marks):
- Minimum 20 programs
Python Programming (Lab Programs)¶
File Handling: 1. Read text file and display contents 2. Count lines, words, characters in file 3. Count vowels and consonants 4. Search for a word in file 5. Copy content from one file to another 6. Read CSV file and display records 7. Add record to CSV file 8. Search in CSV file
Binary Files: 9. Create and read binary file using pickle 10. Store student records in binary file 11. Search student by roll number 12. Update student record
Data Structures: 13. Implement stack with push, pop operations 14. Reverse string using stack 15. Implement queue with enqueue, dequeue
Exception Handling: 16. Handle division by zero 17. File operation with exception handling
Database Management (SQL Programs)¶
Basic Operations: 1. Create database and table 2. Insert records 3. Display all records 4. Search with WHERE clause 5. Update records 6. Delete records 7. Sort records with ORDER BY
Aggregate Functions: 8. Count total records 9. Calculate sum, average of marks 10. Find maximum and minimum marks
GROUP BY: 11. Group by city and count students 12. Group by city and find average marks 13. Use HAVING clause
Python-MySQL Integration: 14. Connect Python to MySQL 15. Insert record from Python 16. Fetch and display records 17. Update record from Python 18. Delete record from Python
Project Work Guidelines ๐¶
Project Requirements: - Real-world problem solving - Use Python programming - Include file handling OR database - Groups of 2-3 students allowed - Originality is important (no plagiarism)
Project Ideas: 1. Student Management System: Store student records, calculate grades 2. Library Management: Book issue/return, fine calculation 3. Inventory Management: Product stock management 4. Hospital Management: Patient records, appointments 5. Banking System: Account management, transactions 6. Quiz Application: Questions, scoring, leaderboard
Project Components: 1. Problem Statement: What problem are you solving? 2. Requirements: What functionality is needed? 3. Code: Python programs 4. Documentation: How to run, screenshots 5. Conclusion: Learning outcomes
Exam Preparation Strategy¶
Theory Exam (70 marks)¶
Time Management (180 minutes): - Section A (MCQ): 25 minutes - Section B (VSA): 35 minutes - Section C (SA): 60 minutes - Section D (LA): 40 minutes - Review: 20 minutes
High-Scoring Topics: 1. Python Programming: 20-25 marks 2. File Handling: 10-12 marks 3. SQL: 10-12 marks 4. Data Structures: 8-10 marks 5. Networks: 5-8 marks
Practical Exam (30 marks)¶
Preparation: - Practice all 20 programs minimum - Speed matters - complete in 2-3 hours - Know syntax by heart - Test programs before exam
Month-wise Study Plan¶
May-July (3 months): - Complete Unit I (Python, Files, Data Structures) - Practice 50+ programs
August-September (2 months): - Complete Unit II (Networks - theory) - Complete Unit III (SQL, Python-MySQL) - Practice 30+ SQL queries
October-December (3 months): - Project work - Revision of all topics - Practice previous year papers
January-February (2 months): - Final revision - Mock tests - Sample papers (CBSE official) - Speed practice
Important Programs to Master¶
Must-Know File Handling (5): 1. Count words in text file 2. Copy file content 3. CSV read and display 4. Binary file student records 5. Search in any file type
Must-Know Stack/Queue (2): 1. Stack implementation 2. Queue implementation
Must-Know SQL (5): 1. CREATE TABLE with constraints 2. INSERT multiple records 3. SELECT with WHERE and ORDER BY 4. GROUP BY with aggregate functions 5. Python-MySQL CRUD operations
Common Board Exam Mistakes¶
Avoid These
Python:
- Not closing files (use with statement)
- Forgetting import csv or import pickle
- Wrong file modes (r, w, a)
- Incorrect exception handling syntax
- Not using mydb.commit() for SQL
SQL: - Forgetting semicolon at end - Wrong aggregate function syntax - HAVING without GROUP BY - Mixing up DDL and DML commands
Theory: - Incomplete answers (give examples!) - Not drawing diagrams for networks - Wrong terminology
Resources¶
Textbooks¶
- NCERT Computer Science Class 12
- Sumita Arora Computer Science with Python
Online Resources¶
Practice Platforms¶
- HackerRank (Python)
- LeetCode (Python problems)
- SQLZoo (SQL practice)
Contact for Help¶
Need assistance with CBSE Class 12 Computer Science?
- WhatsApp: +91 8460441384
- In Class: Weekend batch sessions
- Project Guidance: We help with project selection and coding
- Doubt Clearing: Intensive weekend sessions
Last Batch Before Boards! Weekend-Only intensive coaching for CBSE Class 12 CS Starting May 20, 2026 ยท First month FREE Limited to 25 students
Special Focus: - File handling mastery - SQL query practice - Board exam pattern programs - Previous years solved - Project guidance
Contact: +91 8460441384