CBSE Class 12 Python Revision - Concise Sum-
mary
1. Introduction to Python
Definition: High-level, general-purpose programming language.
Characteristics: - Simple, readable syntax (English-like) - Portable (runs on
Windows, Linux, macOS) - Free and open-source - Case-sensitive (age � Age) -
High-level and interpreted - Developed by Guido van Rossum
Modes of Working: - Interactive Mode: Type statements, see output
immediately - Script Mode: Write complete programs in .py files and run
them
2. Keywords, Identifiers, Variables, Data Types
2.1 Keywords
Reserved words with fixed meaning. Examples: if, else, while, for, True, False,
and, or, not, def, class, etc.
2.2 Identifiers (Naming Rules)
• Can start with alphabet (A-Z, a-z) or underscore (_)
• Can contain alphabets, digits, underscore
• Cannot start with digit
• No special symbols (@, #, %, *, space, etc.)
• Case-sensitive
Valid: a, _ayush, marks1, total_sum Invalid: 1value, @rate, for (keyword)
2.3 Variables
Named location used to store data.
a = 365
russian = 6000
2.4 Data Types
Type Example Description
int 10, -5 Integers
float 3.14, -0.5 Decimal numbers
complex 2+3j Complex numbers
bool True, False Boolean values
1
Type Example Description
str “Python” Strings
list [1, 2, 3] Ordered, mutable collection
tuple (1, 2, 3) Ordered, immutable collection
set {1, 2, 3} Unordered, unique items
dict {“name”: “Ayush”} Key-value pairs
NoneType None No value
3. Comments
Single-line comments start with #
# This is a comment
a = 10 # This is also a comment
4. Operators
4.1 Arithmetic Operators
• + Addition
• - Subtraction
• * Multiplication
• / Division (always returns float)
• // Floor division
• % Modulus (remainder)
• ** Exponent (power)
4.2 Relational Operators
==, !=, >, <, >=, <= (Return True or False)
4.3 Assignment Operators
• Basic: =
• Compound: +=, -=, *=, /=, //=, %=, **=
4.4 Logical Operators
• and: Both conditions TRUE
• or: At least one TRUE
• not: Reverses boolean value
2
4.5 Identity Operators
• is: Same object in memory
• is not: Different objects
4.6 Membership Operators
• in: Check membership in sequences
• not in: Check non-membership
5. Input and Output
5.1 print()
Displays output on screen
print("Hello World")
print(a, b) # Multiple values
5.2 input()
Takes string input from user
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # For integer input
6. Flow of Control: Selection
6.1 if Statement
if condition:
statement(s)
6.2 if-else Statement
if condition:
statement(s)
else:
statement(s)
6.3 if-elif-else Statement
if condition1:
statement(s)
elif condition2:
statement(s)
3
else:
statement(s)
Example:
marks = int(input("Enter marks: "))
if marks > 90:
print("A+")
elif marks > 80:
print("B+")
elif marks > 70:
print("C+")
else:
print("Fail")
7. Indentation
Mandatory in Python. Defines code blocks for if, elif, else, loops, etc.
8. Flow of Control: Repetition (Loops)
8.1 for Loop
for i in range(1, 6):
print(i) # Output: 1 2 3 4 5
for ch in "Python":
print(ch) # Prints each character
8.2 while Loop
i = 1
while i <= 5:
print(i)
i = i + 1
8.3 range() Function
• range(n): 0 to n-1
• range(start, end): start to end-1
• range(start, end, step): with step value
4
9. Strings
Immutable sequence of characters.
String Operations
s = "Python"
print(s[0]) # 'P'
print(s[1:4]) # 'yth'
print(len(s)) # 6
print([Link]()) # 'python'
print([Link]()) # 'PYTHON'
print([Link]('P', 'J')) # 'Jython'
String Methods (Commonly Used)
• find(), count(), startswith(), endswith()
• split(), join(), strip()
10. Lists
Ordered, mutable collection of items.
List Operations
lst = [10, 20, 30]
print(lst[0]) # 10
lst[1] = 50 # Modify element
[Link](40) # Add element
[Link](20) # Remove element
[Link]() # Remove last element
len(lst) # Length
List Methods
• append(), insert(), remove(), pop()
• sort(), reverse()
• index(), count()
Looping Through List
for x in lst:
print(x)
5
11. Tuples
Ordered, immutable collection.
t = (1, 2, 3)
print(t[0]) # 1
# t[0] = 5 # ERROR - immutable
12. Dictionaries
Unordered collection of key-value pairs.
student = {
"name": "Ayush",
"class": 12,
"marks": 95
}
print(student["name"]) # Ayush
student["marks"] = 98 # Update
print(student)
for key in student:
print(key, ":", student[key])
13. Functions
13.1 Built-in Functions
• print(): Display output
• len(): Length of string/list
• range(): Generate sequence
• min(), max(): Find minimum/maximum
• type(): Get data type
• int(), float(), str(): Type conversion
• sum(): Sum of numbers
• sorted(): Sort list
13.2 User-Defined Functions
def function_name(parameter1, parameter2):
# Function body
statement(s)
return value
6
# Call function
function_name(argument1, argument2)
13.3 Parameters vs Arguments
• Parameter: Variable in function definition
• Argument: Value passed when calling function
13.4 Default Parameters
def greet(name="Guest"):
print(f"Hello, {name}")
greet() # Hello, Guest
greet("Ayush") # Hello, Ayush
13.5 Named/Keyword Arguments
def difference(a, b):
print(a - b)
difference(b=5, a=10) # Order doesn't matter
14. Exception Handling
14.1 Error Types
• Syntax Error: Before execution (grammar mistakes)
• Logical Error: Wrong algorithm (produces incorrect output)
• Runtime Error/Exception: During execution (unexpected conditions)
14.2 try-except-else-finally
try:
# Code that might cause error
statement(s)
except:
# Handle error
statement(s)
else:
# Runs if try succeeds (optional)
statement(s)
finally:
# Always runs (optional)
statement(s)
7
14.3 Common Exceptions
Exception Cause
ZeroDivisionError Division by zero
ValueError Wrong data type
TypeError Incompatible types
NameError Variable not defined
IndexError Index out of range
KeyError Dictionary key doesn’t exist
14.4 Handling Specific Exceptions
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
14.5 raise Keyword
age = int(input("Enter age: "))
if age < 18:
raise Exception("You are minor")
14.6 assert Keyword
age = 20
assert age >= 18, "You are minor"
15. File Handling
15.1 File Modes
Mode Purpose Behavior
r Read Opens existing file; error if not found
w Write Creates new/overwrites; deletes old content
a Append Adds to end; preserves old content
rb Read Binary Read binary files
wb Write Binary Write binary files
15.2 Opening and Closing Files
f = open("[Link]", "r")
content = [Link]()
[Link]()
8
15.3 Reading Files
# Read entire file as string
content = [Link]()
# Read one line at a time
line = [Link]()
# Read all lines as list
lines = [Link]()
15.4 Writing Files
f = open("[Link]", "w")
[Link]("Hello World")
[Link]()
15.5 Appending to File
f = open("[Link]", "a")
[Link]("\nNew line")
[Link]()
15.6 File Pointer Operations
position = [Link]() # Get current position
[Link](10) # Move to position 10
content = [Link](50) # Read 50 characters
15.7 Binary Files
# Read binary file
f = open("[Link]", "rb")
data = [Link]()
[Link]()
# Write binary file
f = open("[Link]", "wb")
[Link](data)
[Link]()
15.8 pickle Module (Serialization)
import pickle
# Save Python object as binary
data = {"name": "Ayush", "marks": 95}
f = open("[Link]", "wb")
9
[Link](data, f)
[Link]()
# Load Python object from binary
f = open("[Link]", "rb")
loaded_data = [Link](f)
[Link]()
15.9 CSV Files
import csv
# Read CSV
f = open("[Link]", "r")
reader = [Link](f)
for row in reader:
print(row)
[Link]()
# Write CSV
data = [['Name', 'Age'], ['Ayush', 18]]
f = open("[Link]", "w", newline='')
writer = [Link](f)
[Link](data)
[Link]()
16. Stacks
Linear data structure following LIFO (Last-In-First-Out) principle.
16.1 Stack Properties
1. Linear Data Structure: Data in sequence
2. LIFO Ordering: Last element inserted = first removed
3. Insert/Delete from One End: Both at TOP
4. TOP Pointer: Tracks topmost element
16.2 Stack Operations
PUSH (Insert)
stack = []
[Link](10)
[Link](20) # Stack: [10, 20]
10
POP (Remove)
element = [Link]() # Returns 20, Stack: [10]
16.3 LIFO Verification
stack = []
[Link](10)
[Link](20)
[Link](30)
print([Link]()) # 30 (last inserted, first removed)
print([Link]()) # 20
print([Link]()) # 10
16.4 Errors
• OVERFLOW: PUSH on full stack
• UNDERFLOW: POP on empty stack
16.5 Python Implementation
class Stack:
def __init__(self, max_size=10):
[Link] = []
[Link] = -1
self.max_size = max_size
def push(self, item):
if len([Link]) == self.max_size:
print("OVERFLOW")
else:
[Link](item)
[Link] += 1
def pop(self):
if [Link] == -1:
print("UNDERFLOW")
return None
else:
item = [Link]()
[Link] -= 1
return item
11
17. Database Management (DBMS)
17.1 Key Concepts
• Data: Raw, unorganized facts (bits/bytes)
• Information: Processed, meaningful data
• Database: Collection of interrelated, organized data
• DBMS: Software to manage databases
17.2 Advantages of DBMS
• Eliminates redundancy
• Saves time
• Highly secure
• Easy data access
17.3 SQL: DDL Commands
CREATE TABLE
CREATE TABLE BackBenchers (
SRollNumber INT PRIMARY KEY,
SName VARCHAR(50) NOT NULL,
SCity VARCHAR(20) DEFAULT 'Delhi'
);
ALTER TABLE
ALTER TABLE BackBenchers ADD (Age INT);
ALTER TABLE BackBenchers DROP COLUMN Age;
17.4 SQL: DML Commands
INSERT
INSERT INTO BackBenchers VALUES (1, 'Ayush', 'Delhi');
UPDATE
UPDATE BackBenchers SET SName = 'Priya' WHERE SRollNumber = 1;
DELETE
DELETE FROM BackBenchers WHERE SRollNumber = 1;
17.5 SQL: DQL Command
SELECT
12
SELECT * FROM BackBenchers;
SELECT SName, SCity FROM BackBenchers;
SELECT * FROM BackBenchers WHERE SCity = 'Delhi';
SELECT * FROM BackBenchers WHERE SRollNumber BETWEEN 1 AND 5;
SELECT * FROM BackBenchers WHERE SCity IN ('Delhi', 'Mumbai');
SELECT * FROM BackBenchers WHERE SName LIKE 'A%';
18. Python-SQL Integration (sqlite3)
import sqlite3
# Connect to database
conn = [Link]('[Link]')
cursor = [Link]()
# Create table
[Link]('''CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)''')
# Insert data
[Link]("INSERT INTO students VALUES (1, 'Ayush', 95)")
# Retrieve data
[Link]("SELECT * FROM students")
records = [Link]()
for record in records:
print(record)
# Update data
[Link]("UPDATE students SET marks = 98 WHERE id = 1")
# Delete data
[Link]("DELETE FROM students WHERE id = 2")
# Commit and close
[Link]()
[Link]()
13
19. Practical Programs
Program 1: Simple Calculator
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
choice = int(input("1. Add 2. Subtract 3. Multiply 4. Divide: "))
if choice == 1:
print("Result =", a + b)
elif choice == 2:
print("Result =", a - b)
elif choice == 3:
print("Result =", a * b)
elif choice == 4:
if b != 0:
print("Result =", a / b)
else:
print("Division by zero not allowed")
else:
print("Invalid choice")
Program 2: Count Vowels
s = input("Enter a string: ")
count = 0
for ch in s:
if [Link]() in "aeiou":
count += 1
print("Number of vowels:", count)
Program 3: List Sum and Average
marks = []
n = int(input("How many subjects? "))
for i in range(n):
m = int(input(f"Enter marks of subject {i+1}: "))
[Link](m)
total = sum(marks)
avg = total / n
print("Marks:", marks)
print("Total:", total)
print("Average:", avg)
14
Program 4: File Reading
f = open("[Link]", "r")
lines = [Link]()
print(f"Total lines: {len(lines)}")
for i, line in enumerate(lines, 1):
print(f"Line {i}: {[Link]()}")
[Link]()
Program 5: Stack Operations
stack = []
[Link](10)
[Link](20)
[Link](30)
print([Link]()) # 30
print([Link]()) # 20
print([Link]()) # 10
20. Key Points for Exams
1. Python is case-sensitive and uses indentation
2. Data types: int, float, complex, bool, str, list, tuple, set, dict
3. Operators: Arithmetic, Relational, Logical, Identity, Membership
4. Control flow: if-elif-else, for, while
5. Functions: Built-in and user-defined
6. Exception handling: try-except-else-finally
7. Files: Text, Binary, CSV modes
8. Stacks: LIFO principle, PUSH/POP operations
9. Database: DBMS, SQL DDL/DML/DQL commands
10. Always close files after use
End of Revision Summary
15