CLASS 12
Computer Science
Python Notes
Comprehensive Study Guide | CBSE Board
Covering all important topics for Board Examination
Revision Tour | OOP | Inheritance | File Handling
Data Structures | Recursion | Exception Handling | MySQL with Python
Class 12 Computer Science | Python Notes CBSE Board
Page 2
Class 12 Computer Science | Python Notes CBSE Board
TABLE OF CONTENTS
1. Python Revision Tour ........................................ 3
2. Object Oriented Programming (OOP) ........................... 5
3. Inheritance & Polymorphism .................................. 9
4. File Handling in Python ..................................... 12
5. Exception Handling .......................................... 15
6. Data Structures – Stack & Queue ............................. 17
7. Recursion ................................................... 20
8. MySQL & Database Concepts ................................... 22
9. Python – MySQL Connectivity ................................. 25
10. Important Programs & Quick Revision ......................... 27
Page 3
Class 12 Computer Science | Python Notes CBSE Board
Chapter 1: Python Revision Tour
1.1 Data Types in Python
Python has several built-in data types. Understanding these is fundamental to writing efficient programs.
Data Type Description
int Whole numbers — e.g. 5, -3, 0
float Decimal numbers — e.g. 3.14, -0.5
complex Complex numbers — e.g. 3+4j
str Sequence of characters — e.g. 'Hello'
bool True or False
list Ordered, mutable sequence — [1, 2, 3]
tuple Ordered, immutable sequence — (1, 2, 3)
dict Key-value pairs — {'a': 1}
set Unordered unique elements — {1, 2, 3}
1.2 Operators
Python supports a rich set of operators:
Type Operators
Arithmetic +, -, *, /, //, %, **
Relational ==, !=, >, <, >=, <=
Logical and, or, not
Bitwise &, |, ^, ~, <<, >>
Assignment =, +=, -=, *=, /=, //=, %=, **=
Identity is, is not
Membership in, not in
1.3 Control Structures
Conditional Statements
if condition:
# block
elif another_condition:
# block
else:
# block
Page 4
Class 12 Computer Science | Python Notes CBSE Board
Loops
# for loop
for i in range(1, 11):
print(i)
# while loop
n = 1
while n <= 10:
print(n)
n += 1
Note: range(start, stop, step) — stop is EXCLUSIVE.
1.4 Functions
def greet(name, msg='Hello'):
'''Docstring: greets a person'''
return f'{msg}, {name}!'
print(greet('Riya')) # Hello, Riya!
print(greet('Arjun','Hi')) # Hi, Arjun!
Types of arguments: Positional, Default, Keyword (*args, **kwargs).
★ Important: Local vs Global scope: Use global keyword to modify a global variable inside a function.
1.5 Strings
Strings are immutable sequences. Key methods:
Method Description Example
len() Length of string len('abc') → 3
upper() / lower() Case conversion 'hi'.upper() → 'HI'
strip() Remove whitespace ' hi '.strip() → 'hi'
split() Split into list 'a,b'.split(',') → ['a','b']
find() First index of substring 'hello'.find('l') → 2
replace() Replace substring 'cat'.replace('c','b') → 'bat'
count() Count occurrences 'banana'.count('a') → 3
isdigit() Check if all digits '123'.isdigit() → True
join() Join list to string ','.join(['a','b']) → 'a,b'
Page 5
Class 12 Computer Science | Python Notes CBSE Board
Chapter 2: Object-Oriented Programming (OOP)
OOP is a programming paradigm based on the concept of objects which contain data (attributes) and
behaviour (methods).
Class: Blueprint for creating objects.
Object: Instance of a class.
Attribute: Variable belonging to a class/object.
Method: Function defined inside a class.
Encapsulation: Wrapping data and methods together.
Abstraction: Hiding complex details, showing essentials.
Inheritance: Acquiring properties of a parent class.
Polymorphism: Same interface, different implementations.
2.1 Defining a Class
class Student:
school = 'DPS' # Class attribute
def __init__(self, name, roll):
[Link] = name # Instance attribute
[Link] = roll
def display(self):
print(f'Roll: {[Link]}, Name: {[Link]}')
s1 = Student('Ananya', 101)
[Link]() # Roll: 101, Name: Ananya
print([Link]) # DPS
2.2 Constructor & Destructor
class Demo:
def __init__(self): # Constructor
print('Object created')
def __del__(self): # Destructor
print('Object deleted')
Note: __init__ is automatically called when an object is created. __del__ is called when object is garbage
collected.
2.3 Access Modifiers
Modifier Syntax & Access
Public name — accessible anywhere
Protected _name — accessible in class & subclasses (convention)
Private __name — name-mangled, not directly accessible outside
Page 6
Class 12 Computer Science | Python Notes CBSE Board
class BankAccount:
def __init__(self, bal):
self.__balance = bal # private
def get_balance(self): # getter
return self.__balance
def deposit(self, amt): # setter-like
if amt > 0:
self.__balance += amt
2.4 self Parameter
self refers to the current instance of the class. It must be the first parameter of every instance method.
Python automatically passes the calling object as the first argument.
2.5 Special / Magic Methods (Dunder Methods)
Method Triggered when...
__init__ Object is created
__str__ str(obj) or print(obj) is called
__len__ len(obj) is called
__add__ obj1 + obj2 is used
__eq__ obj1 == obj2 is used
__del__ Object is destroyed
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f'({self.x}, {self.y})'
def __add__(self, other):
return Vector(self.x+other.x, self.y+other.y)
v1 = Vector(1, 2); v2 = Vector(3, 4)
print(v1 + v2) # (4, 6)
Page 7
Class 12 Computer Science | Python Notes CBSE Board
Chapter 3: Inheritance & Polymorphism
3.1 Types of Inheritance
Type Description
Single One child inherits from one parent
Multiple One child inherits from two or more parents
Multilevel Chain: A → B → C
Hierarchical Multiple children from one parent
Hybrid Combination of two or more types
3.2 Single Inheritance Example
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f'{[Link]} makes a sound')
class Dog(Animal): # Single Inheritance
def speak(self): # Method Overriding
print(f'{[Link]} says Woof!')
d = Dog('Bruno')
[Link]() # Bruno says Woof!
3.3 Multiple Inheritance & super()
class Father:
def skills(self): print('Cricket')
class Mother:
def skills(self): print('Cooking')
class Child(Father, Mother):
def skills(self):
super().skills() # calls [Link]()
print('Football')
c = Child()
[Link]() # Cricket Football
Note: Python uses MRO (Method Resolution Order) — C3 linearisation algorithm. Use ClassName.__mro__ to
see the order.
3.4 Multilevel Inheritance
class Vehicle:
def run(self): print('Vehicle runs')
Page 8
Class 12 Computer Science | Python Notes CBSE Board
class Car(Vehicle):
def drive(self): print('Car drives')
class SportsCar(Car):
def race(self): print('SportsCar races')
sc = SportsCar()
[Link](); [Link](); [Link]()
3.5 Polymorphism
Polymorphism means 'many forms'. In Python it is achieved through:
• Method Overriding — child class redefines a parent method
• Duck Typing — any object with required method is accepted
• Operator Overloading — using magic methods
class Shape:
def area(self): return 0
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r * self.r
class Rectangle(Shape):
def __init__(self, l, b): self.l = l; self.b = b
def area(self): return self.l * self.b
for s in [Circle(5), Rectangle(4, 6)]:
print([Link]())
Page 9
Class 12 Computer Science | Python Notes CBSE Board
Chapter 4: File Handling in Python
4.1 File Opening Modes
Mode Meaning
'r' Read (default). Error if file not found.
'w' Write. Creates new file or truncates existing.
'a' Append. Creates new file if not found.
'r+' Read and write. File must exist.
'w+' Write and read. Truncates file.
'rb' / 'wb' Binary read / write
4.2 Text File Operations
# Writing to a file
with open('[Link]', 'w') as f:
[Link]('Hello World\n')
[Link](['Line 2\n', 'Line 3\n'])
# Reading from a file
with open('[Link]', 'r') as f:
content = [Link]() # entire file as string
# OR
line = [Link]() # one line at a time
# OR
lines = [Link]() # list of all lines
# Appending
with open('[Link]', 'a') as f:
[Link]('New line\n')
Note: Always use with statement — it automatically closes the file even if an exception occurs.
4.3 File Pointer Methods
Method Purpose
tell() Returns current file pointer position
seek(n) Moves pointer to byte position n
seek(0) Moves pointer to beginning
seek(0, 2) Moves pointer to end of file
4.4 Binary File Handling with pickle
import pickle
# Writing binary file
Page 10
Class 12 Computer Science | Python Notes CBSE Board
data = {'name': 'Raj', 'marks': 95}
with open('[Link]', 'wb') as f:
[Link](data, f)
# Reading binary file
with open('[Link]', 'rb') as f:
rec = [Link](f)
print(rec) # {'name': 'Raj', 'marks': 95}
# Reading multiple records
with open('[Link]', 'rb') as f:
while True:
try:
rec = [Link](f)
print(rec)
except EOFError:
break
★ Important: EOFError must be caught while reading binary files in a loop to detect end-of-file.
4.5 CSV File Handling
import csv
# Writing CSV
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Marks'])
[Link](['Asha', 98])
# Reading CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)
Page 11
Class 12 Computer Science | Python Notes CBSE Board
Chapter 5: Exception Handling
An exception is an error that occurs during execution. Python provides a structured way to handle
exceptions so the program doesn't crash.
5.1 try-except-else-finally
try:
num = int(input('Enter number: '))
result = 100 / num
except ValueError:
print('Invalid input! Enter a number.')
except ZeroDivisionError:
print('Cannot divide by zero!')
except Exception as e:
print(f'Unexpected error: {e}')
else:
print(f'Result = {result}') # runs if no exception
finally:
print('Execution complete') # always runs
5.2 Common Built-in Exceptions
Exception Cause
ValueError Invalid value passed to function
TypeError Wrong data type used
ZeroDivisionError Division or modulo by zero
IndexError List index out of range
KeyError Key not found in dictionary
FileNotFoundError File does not exist
NameError Variable not defined
AttributeError Invalid attribute access
ImportError Module not found
EOFError End of file reached unexpectedly
OverflowError Result too large to represent
5.3 Raising Exceptions
def check_age(age):
if age < 0:
raise ValueError('Age cannot be negative!')
return age
try:
Page 12
Class 12 Computer Science | Python Notes CBSE Board
check_age(-5)
except ValueError as e:
print(e) # Age cannot be negative!
5.4 User-Defined Exceptions
class NegativeAgeError(Exception):
def __init__(self, msg='Age must be positive'):
super().__init__(msg)
try:
raise NegativeAgeError()
except NegativeAgeError as e:
print(e)
Page 13
Class 12 Computer Science | Python Notes CBSE Board
Chapter 6: Data Structures – Stack & Queue
6.1 Stack
A Stack is a linear data structure following LIFO (Last In, First Out). Operations: push (insert), pop (delete),
peek (top element), isEmpty.
stack = []
# Push
[Link](10)
[Link](20)
[Link](30)
print('Stack:', stack) # [10, 20, 30]
# Pop
if stack:
top = [Link]()
print('Popped:', top) # 30
# Peek
print('Top:', stack[-1]) # 20
# isEmpty
print('Empty?', len(stack) == 0) # False
Note: In Python, list is used to implement stack. append() = push, pop() = pop.
★ Important: Board exam question: Write a Python program to implement a stack using a list for
storing integers.
6.2 Stack using Class
class Stack:
def __init__(self):
self.__data = []
def push(self, item):
self.__data.append(item)
def pop(self):
if not [Link]():
return self.__data.pop()
return 'Underflow'
def peek(self):
if not [Link]():
return self.__data[-1]
return None
def isEmpty(self):
return len(self.__data) == 0
Page 14
Class 12 Computer Science | Python Notes CBSE Board
def display(self):
print(self.__data)
6.3 Queue
A Queue is a linear data structure following FIFO (First In, First Out). Operations: enqueue (insert at rear),
dequeue (delete from front).
from collections import deque
queue = deque()
# Enqueue
[Link]('A')
[Link]('B')
[Link]('C')
print('Queue:', list(queue)) # ['A', 'B', 'C']
# Dequeue
front = [Link]()
print('Dequeued:', front) # A
print('Queue:', list(queue)) # ['B', 'C']
Note: Use [Link] for efficient Queue operations. List-based queue is slow due to O(n) for pop(0).
6.4 Comparison: Stack vs Queue
Feature Stack Queue
Principle LIFO FIFO
Insert at Top Rear
Delete from Top Front
Python impl [Link]() / pop() [Link]() / popleft()
Real-world eg Back button, Undo Print queue, Ticket counter
Page 15
Class 12 Computer Science | Python Notes CBSE Board
Chapter 7: Recursion
A function that calls itself is called a recursive function. Every recursive function must have a base case to
stop infinite recursion.
7.1 Factorial
def factorial(n):
if n == 0 or n == 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(5)) # 120
7.2 Fibonacci Sequence
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
for i in range(8):
print(fib(i), end=' ') # 0 1 1 2 3 5 8 13
7.3 Sum of Digits
def sum_digits(n):
if n < 10:
return n
return (n % 10) + sum_digits(n // 10)
print(sum_digits(1234)) # 10
7.4 Recursion vs Iteration
Basis Recursion Iteration
Definition Function calls itself Uses loop constructs
Memory Uses call stack (more memory) Uses less memory
Speed Generally slower Generally faster
Code size Smaller, elegant Longer
Risk Stack overflow if deep No such risk
★ Important: Tail recursion optimisation is NOT performed by Python. Each recursive call adds a
frame to the call stack. Default recursion limit is 1000 ([Link]()).
Page 16
Class 12 Computer Science | Python Notes CBSE Board
Chapter 8: MySQL & Database Concepts
8.1 Key Terminology
DBMS: Database Management System — software to manage databases.
RDBMS: Relational DBMS — stores data in tables (rows & columns).
Table: Collection of related records (like a 2D matrix).
Tuple/Row: A single record in a table.
Attribute/Column: A field/property of each record.
Primary Key: Uniquely identifies each row. Cannot be NULL or duplicate.
Foreign Key: References primary key of another table.
Candidate Key: All attributes that can be primary keys.
Degree: Number of columns in a table.
Cardinality: Number of rows in a table.
8.2 DDL, DML, DQL Commands
Category Full Form Commands
DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE
DML Data Manipulation Language INSERT, UPDATE, DELETE
DQL Data Query Language SELECT
DCL Data Control Language GRANT, REVOKE
TCL Transaction Control Language COMMIT, ROLLBACK, SAVEPOINT
8.3 Important SQL Queries
-- Create database & table
CREATE DATABASE school;
USE school;
CREATE TABLE student(
roll INT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
class INT,
marks FLOAT
);
-- Insert records
INSERT INTO student VALUES(1,'Asha',12,95.5);
INSERT INTO student VALUES(2,'Raj',11,88.0);
-- Select queries
SELECT * FROM student;
SELECT name, marks FROM student WHERE marks > 90;
SELECT * FROM student ORDER BY marks DESC;
SELECT * FROM student WHERE name LIKE 'A%';
SELECT class, COUNT(*) FROM student GROUP BY class;
Page 17
Class 12 Computer Science | Python Notes CBSE Board
SELECT MAX(marks), MIN(marks), AVG(marks) FROM student;
-- Update & Delete
UPDATE student SET marks=97 WHERE roll=1;
DELETE FROM student WHERE marks < 50;
-- ALTER table
ALTER TABLE student ADD COLUMN grade CHAR(2);
ALTER TABLE student MODIFY marks INT;
ALTER TABLE student DROP COLUMN grade;
8.4 Aggregate Functions
Function Purpose
COUNT(*) Count number of rows
SUM(col) Sum of values in column
AVG(col) Average of values
MAX(col) Maximum value
MIN(col) Minimum value
8.5 Constraints
NOT NULL: Column cannot have NULL value
UNIQUE: All values must be different
PRIMARY KEY: Unique + Not Null
FOREIGN KEY: References column of another table
DEFAULT: Sets a default value
CHECK: Ensures condition is met
Page 18
Class 12 Computer Science | Python Notes CBSE Board
Chapter 9: Python – MySQL Connectivity
Python connects to MySQL using the mysql-connector-python library. This allows executing SQL queries
from Python programs.
9.1 Installation & Connection
# Install (run in terminal)
pip install mysql-connector-python
import [Link]
con = [Link](
host='localhost',
user='root',
password='yourpassword',
database='school'
)
if con.is_connected():
print('Connected successfully!')
9.2 Cursor Object
A cursor acts as a pointer to execute SQL queries and retrieve results.
cursor = [Link]()
# Execute a query
[Link]('SELECT * FROM student')
# Fetch results
rows = [Link]() # all rows as list of tuples
row = [Link]() # next single row
rows = [Link](3) # next 3 rows
for row in rows:
print(row)
9.3 INSERT / UPDATE / DELETE from Python
# Insert a record
sql = 'INSERT INTO student VALUES(%s,%s,%s,%s)'
data = (3, 'Priya', 12, 91.0)
[Link](sql, data)
[Link]() # MUST commit for DML operations
print([Link], 'record inserted')
# Update
sql = 'UPDATE student SET marks=%s WHERE roll=%s'
[Link](sql, (99, 3))
[Link]()
Page 19
Class 12 Computer Science | Python Notes CBSE Board
# Delete
[Link]('DELETE FROM student WHERE roll=%s', (3,))
[Link]()
Note: Always call [Link]() after INSERT/UPDATE/DELETE. Without it, changes are not saved to the
database.
9.4 Complete CRUD Example
import [Link]
con = [Link](host='localhost',
user='root', password='pass', database='school')
cur = [Link]()
def add_student(roll, name, marks):
[Link](
'INSERT INTO student(roll,name,marks) VALUES(%s,%s,%s)',
(roll, name, marks))
[Link]()
def search_student(roll):
[Link]('SELECT * FROM student WHERE roll=%s',(roll,))
return [Link]()
def display_all():
[Link]('SELECT * FROM student')
for r in [Link](): print(r)
add_student(5, 'Kiran', 87)
print(search_student(5))
display_all()
[Link]()
★ Important: Closing the connection with [Link]() is important to free resources.
Page 20
Class 12 Computer Science | Python Notes CBSE Board
Chapter 10: Important Programs & Quick Revision
10.1 Frequently Asked Programs
A. Binary Search
def binary_search(lst, key):
low, high = 0, len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == key: return mid
elif lst[mid] < key: low = mid + 1
else: high = mid - 1
return -1
B. Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-1-i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
C. Count Words in a File
with open('[Link]', 'r') as f:
data = [Link]()
words = [Link]()
print('Word count:', len(words))
D. Count Specific Lines in File
with open('[Link]', 'r') as f:
count = sum(1 for line in f if 'Python' in line)
print('Lines with Python:', count)
10.2 Quick Revision: One-Liners
Concept Explanation
list vs tuple list is mutable; tuple is immutable
break vs continue break exits loop; continue skips current iteration
pass null statement — placeholder, does nothing
lambda Anonymous one-line function: lambda x: x*2
map() Applies function to each element of iterable
filter() Filters elements based on condition
list comprehension [expr for item in iterable if cond]
*args Variable number of positional arguments
Page 21
Class 12 Computer Science | Python Notes CBSE Board
**kwargs Variable number of keyword arguments
__name__=='__main__' Block runs only when file is run directly
10.3 Board Exam Tips
• Always write the complete class definition with __init__ in OOP questions.
• In file handling, mention 'with' statement and explain why it is preferred.
• For stack/queue questions, write push/pop or enqueue/dequeue clearly.
• In SQL, remember semicolons and proper syntax. Case doesn't matter for keywords.
• In Python-MySQL, always include [Link]() for DML and [Link]() for SELECT.
• For recursion, always define the base case clearly in your code and explanation.
• Draw memory diagrams for inheritance wherever asked — fetch extra marks!
• Practice at least 5 complete programs for file handling and OOP.
Best of Luck for Your Board Examinations!
Page 22