Class 12 Computer Science (Python & SQL) Quick Reference & Cheat Sheet
Complete chapter-wise revision guide and cheat sheet for CBSE Class 12 Computer Science (Python 3.x, File Handling, Stacks, Computer Networks, SQL & MySQL Connectivity) as per NCERT 2026-27 syllabus.
Jump to Chapter:
Key Principles
- Mutability vs Immutability: Immutable types (int, float, bool, string, tuple) cannot be altered in-place; any modification creates a new object in memory. Mutable types (list, dict, set) allow in-place modification of elements.
- String & List Slicing: General syntax `seq[start : stop : step]`. Indexing starts at 0 (positive) or -1 (negative/reverse). Stop boundary is strictly EXCLUSIVE.
- Dictionary Mechanics: Stores key-value mappings. Keys must be of an immutable hashable data type (int, string, tuple). Values can be any arbitrary data type.
- List Comprehensions: Compact concise syntax `[expression for item in iterable if condition]` providing high readability and fast execution.
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | General Sequence Slicing Rule | seq[start : stop : step] extracts elements from index start up to stop - 1 in strides of step | If step is negative, slice traverses backwards and start must be greater than stop (e.g. s[::-1] reverses string s). |
| 2 | String Inversion (Reverse Slicing) | reversed_str = original_str[::-1] | Idiomatic Python technique to reverse strings or tuples in O(N) time complexity. |
| 3 | List In-Place Append vs Extend | list.append(x) adds x as single element; list.extend(iterable) appends each element of iterable | Append nests the container; extend unpacks and concatenates the elements. |
| 4 | Dictionary Safe Value Access | dict.get(key, default_value) | Retrieves value associated with key without raising a KeyError if the key is missing. |
| 5 | Floor Division and Modulo Identity | a = (a // b) × b + (a % b) | Python integer division rounds down toward negative infinity; modulo result always has the same sign as divisor b. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Function Definition & Anatomy: Defined using `def fname(params):`. Consists of header, parameter list, docstring, body statements, and optional `return` statement (defaults to returning `None`).
- Types of Arguments: 1) Positional arguments (matched by order), 2) Default arguments (default values assigned right-to-left in signature), 3) Keyword arguments (passed by parameter name, order irrelevant).
- Scope of Variables & LEGB Rule: Python resolves variable names in strict hierarchy: Local (inside current function) -> Enclosing (nested outer function) -> Global (module level) -> Built-in (Python built-in namespace).
- `global` Keyword: Used inside a function to modify a variable declared at the module level.
- Recursion: A programming technique where a function calls itself directly or indirectly to solve a smaller instance of the same problem. Must have: 1) Base case (terminating condition), 2) Recursive case (progressing toward base case).
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | LEGB Scope Resolution Hierarchy | Scope Search Order: Local -> Enclosing -> Global -> Built-in | Python searches innermost local scope first and broadens outwards until matching name is found or NameError raised. |
| 2 | Default Parameter Right-to-Left Rule | Non-default arguments cannot follow default arguments: def f(a, b=2, c=3) is valid; def f(a=1, b) is SYNTAX ERROR | All positional arguments without defaults must precede parameters with default values. |
| 3 | Recursive Factorial Mathematical Function | fact(n) = 1 if n == 0 or n == 1 else n × fact(n - 1) | Classic recursion with base case n <= 1 and O(n) call stack depth. |
| 4 | Recursive Fibonacci Mathematical Function | fib(n) = n if n <= 1 else fib(n - 1) + fib(n - 2) | Branching tree recursion with exponential O(2^n) time complexity unless memoized. |
| 5 | Recursive Binary Search Time Complexity | T(n) = T(n / 2) + O(1) -> Worst-case Time Complexity = O(log2 n) | Halves search interval at each recursive call on sorted arrays. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Errors vs Exceptions: Syntax errors (parsing errors caught during compilation before execution) vs Exceptions (runtime anomalies that disrupt normal instruction flow, e.g. division by zero, missing file).
- Handling Constructs: `try` block (contains code that may raise an exception), `except` block (catches and handles specific exception), `else` block (executes ONLY if no exception occurred in try), `finally` block (executes ALWAYS, used for clean-up/resource closing).
- Explicit Exception Raising: Using the `raise` keyword to trigger custom or built-in exceptions when business constraints are violated.
- Common Built-in Exceptions: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError, IOError, ImportError, NameError.
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | Standard Try-Except-Else-Finally Syntax Template | try: [risky code] except ExceptionType as e: [handler] else: [runs on success] finally: [clean-up runs always] | Complete flow control ensuring resources like open files and sockets are closed reliably. |
| 2 | Multiple Exception Handling in Single Block | except (ZeroDivisionError, ValueError, TypeError) as e: | Catches any of the grouped exception types using a tuple syntax. |
| 3 | Explicit Exception Raising with Custom Message | if condition: raise ValueError('Detailed error explanation') | Forces execution into the nearest matching except block or terminates script with traceback. |
| 4 | Assertion Statement Validation | assert condition, 'Assertion error message' | Debugging tool to verify internal invariant conditions. |
| 5 | ZeroDivisionError Trigger Condition | Trigger: b == 0 in a / b, a // b, or a % b | Raised when division or modulo denominator evaluates to numerical zero. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- File Types: 1) Text Files (.txt): Human-readable characters encoded in ASCII/UTF-8; each line terminated by End-of-Line (EOL, `\n`). 2) Binary Files (.dat): Stores raw bytes directly without translation (exact memory dump); requires `pickle` module. 3) CSV Files (.csv): Comma-Separated Values storing tabular data in plain text; requires `csv` module.
- File Modes: Read (`'r'`), Write (`'w'`, overwrites), Append (`'a'`), Read & Write (`'r+'`, `'w+'`, `'a+'`). Binary modes append `'b'` (`'rb'`, `'wb'`, `'ab'`).
- Text File Reading Methods: `read()` (reads entire file as single string), `readline()` (reads single line as string including newline), `readlines()` (reads all lines as a list of strings).
- Pickle Module (Binary): `pickle.dump(object, file_handle)` serializes object to binary file; `pickle.load(file_handle)` deserializes binary stream back into Python object. Must handle `EOFError` when reading in a loop.
- CSV Module: `csv.reader(file_handle)` returns an iterable row reader; `csv.writer(file_handle)` creates writer; `writer.writerow(list)` writes single row; `writer.writerows(list_of_lists)` writes multiple rows. Use `newline=''` when opening CSV files.
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | Context Manager Safe File Opening Formula | with open(filename, mode) as file_handle: [operations] | Automatically calls file.close() upon exiting the block, even if an exception is raised. |
| 2 | Text File Read Return Types | f.read() -> str; f.readline() -> str; f.readlines() -> list of str | read() reads full content; readline() reads line-by-line; readlines() loads lines into list. |
| 3 | File Pointer Positioning Methods | f.tell() returns current byte position; f.seek(offset, whence) moves pointer | In text files, whence is restricted to 0 (or offset 0 for 1 and 2); binary files allow arbitrary offsets. |
| 4 | Binary Pickling Serialization | pickle.dump(data_object, binary_file_handle) | Serializes in-memory Python structures (lists, dicts) into persistent binary bytecode format. |
| 5 | Binary Unpickling Deserialization Loop | while True: try: data = pickle.load(f) ... except EOFError: break | Standard pattern for sequentially reading multiple records from a binary file until End-of-File. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Data Structure Classification: Linear (elements form a sequential sequence: List, Stack, Queue) vs Non-Linear (elements organized hierarchically: Trees, Graphs).
- Stack Definition: A linear data structure that follows the LIFO (Last In, First Out) or FILO (First In, Last Out) principle. All insertions and deletions take place at a single end called TOP.
- Stack Operations: 1) PUSH (inserting element at top), 2) POP (deleting element from top), 3) PEEK / INSPECT (viewing top element without removing it), 4) isEmpty (testing if stack has zero elements).
- Stack Exceptional Conditions: Overflow (attempting to push into a full stack of fixed capacity) and Underflow (attempting to pop from an empty stack).
- Queue Definition: A linear data structure that follows the FIFO (First In, First Out) principle. Insertions happen at REAR (Enqueue), deletions happen at FRONT (Dequeue).
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | Stack Implementation via Python List Mapping | Top of Stack = Last Element (L[-1]); PUSH = L.append(item); POP = L.pop() | Python list amortized O(1) append and pop operations at the end make it the ideal implementation for a stack. |
| 2 | Stack Underflow Condition | Underflow: len(stack) == 0 (or stack == []) when pop() or peek() is attempted | Must be guarded by checking `if len(s) == 0: print('Underflow')` before calling pop(). |
| 3 | Stack Overflow Condition (Bounded Stack) | Overflow: len(stack) == MAX_CAPACITY when push() is attempted | In Python dynamic lists, memory is dynamically resized, but bounded stacks enforce capacity limit. |
| 4 | Stack PEEK / Top Element Inspection | peek(s) = None if len(s) == 0 else s[-1] | Accesses top element in O(1) time without mutating stack structure. |
| 5 | Stack Display from Top to Bottom | for i in range(len(stack) - 1, -1, -1): print(stack[i]) | Traverses list in reverse to show LIFO order visually. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Evolution of Networking: ARPANET (1969, US DoD, packet switching), NSFNET (high-capacity academic backbone), Internet (worldwide interconnection of heterogeneous networks via TCP/IP).
- Network Types: PAN (Personal Area Network, Bluetooth, < 10m), LAN (Local Area Network, office building, < 1km), MAN (Metropolitan Area Network, cable TV, city-wide, < 50km), WAN (Wide Area Network, country/global, Internet).
- Network Topologies: Bus (single backbone coaxial cable, terminator at ends), Star (central hub/switch, easiest to troubleshoot, most common), Tree (hierarchical combination of star and bus), Mesh (every node connected to every other, maximum redundancy), Ring (token ring, circular).
- Transmission Media: Guided / Wired (Twisted Pair [UTP/STP, RJ45], Coaxial Cable [BNC], Optical Fiber [total internal reflection, highest speed, immunity to EMI]) vs Unguided / Wireless (Radio waves [omnidirectional, FM/cellular], Micro-waves [line-of-sight, towers], Infrared [short range, TV remote], Satellite communication).
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | Mesh Topology Cable Requirement Formula | Number of Cables required in Full Mesh = (n × (n - 1)) / 2 where n is number of nodes | Every computer connects to every other; e.g. 10 computers require 10 × 9 / 2 = 45 dedicated cables. |
| 2 | Mesh Topology Ports per Node Formula | I/O Ports required per device in Full Mesh = n - 1 | Each individual computer must have n - 1 network interface cards/ports. |
| 3 | Bandwidth and Data Transfer Rate Conversion | 1 Byte = 8 bits; 1 Kbps = 1,000 bps; 1 Mbps = 1,000,000 bps; 1 Gbps = 1,000 Mbps | Network speed is rated in bits per second (lowercase b); file storage is rated in Bytes (uppercase B). |
| 4 | Download Time Estimation Formula | Download Time (seconds) = File Size in bits / Bandwidth Speed in bps | Estimates theoretical transfer time over a given link capacity. |
| 5 | Server Placement Rule (80-20 Rule) | Server should be installed in the wing/block having the MAXIMUM number of computers | Standard CBSE case-study rule: minimizes traffic congestion and overall cabling costs. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Hardware Devices: Modem (Modulator-Demodulator: converts analog to digital & vice versa), RJ45 (8-pin Ethernet connector), Hub (broadcast device, physical layer), Switch (intelligent packet filter based on MAC address, data link layer), Repeater (amplifies attenuated signals), Gateway (connects dissimilar networks with different protocols), Router (finds optimal packet path using IP routing tables).
- Network Protocols: TCP/IP (Transmission Control Protocol: reliable packet delivery; IP: logical addressing), IPv4 (32-bit, 4 octets e.g. 192.168.1.1) vs IPv6 (128-bit hexadecimal), MAC Address (48-bit physical hardware address burned into NIC, 6 pairs of hex digits separated by hyphens/colons).
- Application Protocols: HTTP (port 80) vs HTTPS (port 443, SSL/TLS encrypted), FTP (file transfer, port 20/21), SMTP (Simple Mail Transfer Protocol for SENDING emails), POP3/IMAP (for RECEIVING emails), VoIP (Voice over IP).
- Web Technologies: DNS (Domain Name System: translates human domain names into numerical IP addresses), URL anatomy: `protocol://domain:port/path?query#hash`, Static vs Dynamic web pages, Cookies vs Cache.
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | IPv4 vs IPv6 Address Capacity Formula | IPv4 Total Addresses = 2^32 (approx 4.29 billion); IPv6 Total Addresses = 2^128 (approx 3.4 × 10^38) | IPv6 completely eliminates the global address exhaustion crisis of 32-bit IPv4. |
| 2 | MAC Address Bit Length & Format | MAC Length = 48 bits = 6 Bytes = 12 Hexadecimal Digits (e.g. 00:1A:2B:3C:4D:5E) | First 3 bytes identify manufacturer (OUI); last 3 bytes are unique device serial. |
| 3 | URL Structural Anatomy | URL = scheme://domain:port/path?query_string#fragment_id | Standard uniform resource locator syntax specification (RFC 3986). |
| 4 | Hub vs Switch Collision Domains | Hub: 1 Shared Collision Domain for all ports; Switch: Each port has its own dedicated Collision Domain | Switches eliminate frame collisions by buffering and unicasting packets to destination ports. |
| 5 | DNS Resolution Mapping Identity | DNS: Domain Name (e.g. www.cbse.gov.in) <-> IP Address (e.g. 164.100.107.13) | Distributed hierarchical directory service converting human-friendly strings to network routing integers. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Relational Model (E.F. Codd 1970): Organizes data into two-dimensional tables called Relations composed of rows (Tuples) and columns (Attributes).
- Core Terminology: Relation (Table), Attribute (Column / Field), Tuple (Row / Record), Domain (pool of legal atomic values for an attribute), Degree (number of attributes), Cardinality (number of tuples).
- Relational Keys: 1) Candidate Key (minimal superkey capable of uniquely identifying a tuple), 2) Primary Key (chosen candidate key; cannot contain NULL), 3) Alternate Key (candidate keys not selected as primary key), 4) Foreign Key (attribute in a table whose values reference the primary key of another table).
- Integrity Constraints: Entity Integrity (primary key cannot be NULL) and Referential Integrity (foreign key value must either match an existing primary key value in parent table or be NULL).
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | Degree of a Relation Formula | Degree = Total Number of Attributes (Columns) in the Relation | Does not change when rows are added or deleted. |
| 2 | Cardinality of a Relation Formula | Cardinality = Total Number of Tuples (Rows) currently stored in the Relation | Increases with INSERT and decreases with DELETE. |
| 3 | Cartesian Product Degree & Cardinality Identities | If R1 has Degree D1, Card C1 and R2 has Degree D2, Card C2 -> R1 × R2 has Degree = D1 + D2 and Cardinality = C1 × C2 | Cross product pairs every row of first table with every row of second table. |
| 4 | Candidate Key Minimal Superkey Property | K is a Candidate Key iff K uniquely identifies all tuples AND no proper subset of K uniquely identifies all tuples | Ensures uniqueness without redundant attributes. |
| 5 | Alternate Keys Formula | Number of Alternate Keys = Total Candidate Keys - 1 (the Primary Key) | Unselected candidate keys that remain viable unique identifiers. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- SQL Classification: DDL (Data Definition Language: CREATE, ALTER, DROP - modifies schema structure) vs DML (Data Manipulation Language: INSERT, SELECT, UPDATE, DELETE - manipulates row instances).
- Table Constraints: PRIMARY KEY (unique + not null), NOT NULL (cannot be left empty), UNIQUE (all values distinct, allows nulls), DEFAULT (fallback value), CHECK (validates condition), FOREIGN KEY ... REFERENCES (referential integrity).
- DML Query Clauses: SELECT column_list FROM table WHERE condition ORDER BY col [ASC|DESC] LIMIT n.
- Pattern Matching & Operators: `LIKE '%abc'` (ends with abc), `LIKE '_a%'` (second char is 'a'), `BETWEEN low AND high` (inclusive), `IN (val1, val2)`, `IS NULL` / `IS NOT NULL` (checking missing data).
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | CREATE TABLE DDL Syntax Template | CREATE TABLE table_name (col1 datatype constraints, col2 datatype, PRIMARY KEY (col1), FOREIGN KEY (col2) REFERENCES parent(id)); | Defines new relational structure with column specifications and integrity constraints. |
| 2 | ALTER TABLE Schema Modifications | ALTER TABLE T ADD col datatype; ALTER TABLE T DROP COLUMN col; ALTER TABLE T MODIFY col new_datatype; | Modifies table definition without destroying existing stored records. |
| 3 | DROP TABLE vs DELETE FROM Distinction | DROP TABLE T removes table schema + data; DELETE FROM T removes rows keeping schema intact | DROP is DDL (cannot rollback); DELETE is DML (can rollback). |
| 4 | INSERT INTO Syntax Template | INSERT INTO table_name (col1, col2) VALUES (val1, val2); | Adds a new tuple to the relation; strings and dates must be enclosed in single quotes. |
| 5 | UPDATE Statement Syntax | UPDATE table_name SET col1 = val1, col2 = val2 WHERE condition; | Modifies attribute values in existing rows; omitting WHERE updates ALL rows. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- SQL Aggregate Functions: Perform calculation on a column of values across multiple rows and return a SINGLE scalar value: `COUNT(*)`, `COUNT(col)`, `SUM()`, `AVG()`, `MIN()`, `MAX()`. All aggregate functions (except `COUNT(*)`) ignore NULL values.
- `COUNT(*)` vs `COUNT(column)`: `COUNT(*)` counts total rows including rows with NULLs; `COUNT(column)` counts only rows where the specified column is NOT NULL.
- GROUP BY Clause: Groups rows having the same values in specified columns into summary rows. Any non-aggregate column in SELECT list MUST appear in GROUP BY clause.
- HAVING Clause vs WHERE Clause: `WHERE` filters individual rows BEFORE grouping is applied; `HAVING` filters aggregated groups AFTER `GROUP BY` is applied (can contain aggregate functions).
- Table Joins: Combining rows from two or more tables based on a common related column: Equi-join (`table1.id = table2.id`), Natural Join (automatically equates columns with identical names and removes duplicate column from output), Cross Join (Cartesian product).
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | Standard SQL Query Execution Order | 1. FROM/JOIN -> 2. WHERE -> 3. GROUP BY -> 4. HAVING -> 5. SELECT -> 6. DISTINCT -> 7. ORDER BY -> 8. LIMIT | Logical query processing pipeline explaining why alias names cannot be used in WHERE clauses. |
| 2 | COUNT(*) vs COUNT(col) Null Handling Identity | COUNT(*) = Total Rows; COUNT(col) = Total Rows - Rows where col IS NULL | Crucial difference in SQL aggregation. |
| 3 | AVG Function Null Exclusion Formula | AVG(col) = SUM(col) / COUNT(col) [Denominator does NOT count NULL rows] | Excluding NULL from denominator prevents downward skew in averages. |
| 4 | GROUP BY with HAVING Filter Template | SELECT col, COUNT(*), AVG(salary) FROM EMP GROUP BY col HAVING COUNT(*) > 5; | HAVING filters groups; WHERE cannot filter aggregate conditions like `AVG(salary) > 50000`. |
| 5 | Equi-Join Two Table Syntax | SELECT T1.col, T2.col FROM Table1 T1, Table2 T2 WHERE T1.common_key = T2.common_key; | Combines matching records using explicit foreign key equality in WHERE clause. |
Showing 5 of 10 formulas. View all 10 formulas →
Key Principles
- Database Connectivity: Interfacing Python backend scripts with MySQL relational database using `mysql.connector` driver module.
- Connection Workflow: 1) Import driver (`import mysql.connector`), 2) Establish connection object (`con = mysql.connector.connect(host, user, password, database)`), 3) Create cursor object (`cur = con.cursor()`), 4) Execute SQL query (`cur.execute(query)`), 5) Fetch result rows (`fetchone()`, `fetchall()`, `fetchmany(n)`), 6) Commit transaction for DML changes (`con.commit()`), 7) Close cursor and connection (`cur.close()`, `con.close()`).
- Fetching Methods: `cur.fetchone()` returns single tuple or `None`; `cur.fetchall()` returns list of all tuples; `cur.fetchmany(n)` returns list of next n tuples.
- Transaction Commit & Rollback: DML statements (INSERT, UPDATE, DELETE) modify the database buffer; changes are made permanent ONLY when `con.commit()` is called. `con.rollback()` undoes uncommitted changes.
| # | Topic | Formula | Conditions & Meaning |
|---|---|---|---|
| 1 | MySQL Connection Establishment Formula | con = mysql.connector.connect(host='localhost', user='root', password='mypassword', database='schooldb') | Returns a MySQLConnection object; raises Error if credentials or server are invalid. |
| 2 | Cursor Object Creation | cursor = con.cursor() | Creates working cursor to execute SQL commands and traverse query result sets. |
| 3 | Parameterized Query (SQL Injection Prevention) | cur.execute('INSERT INTO student VALUES (%s, %s, %s)', (roll, name, marks)) | Uses %s placeholders; driver safely escapes and formats variables. |
| 4 | Fetching All Records | records = cur.fetchall() -> list of tuples [ (r1_c1, r1_c2), (r2_c1, r2_c2), ... ] | Loads entire result set into Python list; returns empty list if no rows. |
| 5 | Fetching Single Next Record | row = cur.fetchone() -> tuple (c1, c2, ...) or None if end of result set | Conserves memory by iterating one record at a time in a while loop. |
Showing 5 of 10 formulas. View all 10 formulas →