Python Programming Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
Introduction to Python
Module 2
Data Structures & Type Conversion
Module 3
Flow Control & Functions
Module 4
Packages, Files, Exception Handling & OOP
Module 5
Regular Expressions & Database Programming
Read Module Notes Online
Module I: Introduction to Python
Chapter 1: Fundamentals of Computing and Algorithmic Problem Solving
1.1 Identification of Computational Problems
Computing begins with the precise formulation of a computational problem—a well-defined specification that maps a set of valid inputs to a desired set of outputs through a finite sequence of deterministic transformations. Before a single line of Python code is written, a software engineer must analyze the problem domain, identify all constraints, boundary conditions, and data types, and decompose complex requirements into manageable sub-problems. A computational problem is formally characterized by three elements: the problem instance (the specific input data supplied at runtime), the preconditions (assumptions that must hold true about the input before execution begins), and the postconditions (guarantees that must hold true about the output once execution terminates).
In academic and industrial software development, problem identification follows a structured workflow. First, requirements analysis clarifies what the system must compute rather than how it should be implemented. For example, finding the greatest common divisor (GCD) of two positive integers, sorting a list of student examination records, or computing compound interest over a multi-year horizon are all distinct computational problems. Second, edge cases—such as zero inputs, negative values, empty strings, or division by zero—are cataloged so that the resulting solution remains robust under unexpected conditions. Third, computational feasibility is evaluated in terms of time complexity (how execution steps grow with input size ) and space complexity (how auxiliary memory grows with ).
1.2 Algorithms: Properties and Design Principles
An algorithm is a finite, unambiguous, step-by-step procedure for solving a computational problem. Every valid algorithm must satisfy five classical properties: finiteness (it must terminate after a finite number of steps for all valid inputs), definiteness (each instruction must be precisely specified with zero ambiguity), input (zero or more well-defined quantities are supplied externally), output (at least one quantity bearing a specified relation to the inputs is produced), and effectiveness (every basic operation must be sufficiently elementary to be carried out exactly in finite time).
Algorithmic design relies on three fundamental control structures proven sufficient to express any computable function: sequence (executing steps one after another in linear order), selection (choosing between alternative paths based on a Boolean condition), and iteration (repeating a block of operations while a termination criterion remains unmet). Modular decomposition further breaks large algorithms into self-contained sub-algorithms, improving readability, testability, and reuse.
1.3 Flowcharts and Pseudocode
Before translating an algorithm into Python syntax, developers express its logic using language-independent planning notations: flowcharts and pseudocode. A flowchart is a standardized graphical diagram representing control flow using geometric symbols connected by directional arrows. Flowcharts provide immediate visual clarity for branching logic and loops, making them valuable for documentation, peer review, and debugging.
| Flowchart Symbol | Standard Shape | Semantic Role | Typical Example |
|---|---|---|---|
| Terminal | Oval / Rounded Rectangle | Marks the entry point (Start) or exit point (Stop/End) of an algorithm. | Start, Stop |
| Input / Output | Parallelogram | Represents reading external data or displaying computed results. | Read N, Print Sum |
| Process | Rectangle | Denotes arithmetic calculations, variable assignments, or internal state updates. | Sum ← Sum + i |
| Decision | Diamond | Evaluates a Boolean predicate with two or more labeled outgoing branches (True/False). | Is i ≤ N? |
| Flowline | Directed Arrow | Indicates the sequential order of execution between symbols. | Connects Process to Decision |
| Connector | Small Circle | Links distant flowchart segments across page boundaries without crossing lines. | Page jump label A |
Pseudocode is a structured, plain-English textual notation that mimics high-level programming constructs without enforcing strict compiler or interpreter syntax. Unlike flowcharts, pseudocode scales effortlessly to large algorithms and maps almost line-for-line onto Python statements. Standard pseudocode conventions use uppercase keywords such as INPUT, OUTPUT, IF ... THEN ... ELSE ... ENDIF, WHILE ... DO ... ENDWHILE, and FOR ... TO ... ENDFOR, paired with clear indentation to signify block nesting.
# Pseudocode:
# ALGORITHM Factorial(n)
# INPUT: Non-negative integer n
# OUTPUT: n!
# IF n < 0 THEN RETURN "Invalid input"
# SET result <- 1
# FOR i <- 1 TO n DO
# SET result <- result * i
# ENDFOR
# RETURN result
def factorial(n):
if n < 0:
raise ValueError("Factorial requires a non-negative integer.")
result = 1
for i in range(1, n + 1):
result *= i
return result
print("5! =", factorial(5))Chapter 2: Introduction to Python and Execution Modes
2.1 History and Key Features of Python
Python is a high-level, general-purpose, interpreted programming language designed in the late 1980s and first released in 1991 by Guido van Rossum. Its design philosophy emphasizes code readability, expressive syntax, and developer productivity, summarized by the principle that programs should be written for humans to read and only incidentally for machines to execute. Python is widely adopted across web backend engineering, scientific computing, data analytics, artificial intelligence, cybersecurity automation, and academic computer science instruction.
| Feature | Technical Explanation | Developer Benefit |
|---|---|---|
| Readable Syntax | Uses significant whitespace indentation instead of curly braces or begin/end delimiters. | Enforces uniform visual structure and minimizes syntactic noise. |
| Interpreted Execution | Source code is compiled internally to bytecode (.pyc) and executed by the Python Virtual Machine (PVM). | Eliminates manual compile-link cycles and enables rapid prototyping. |
| Dynamic Typing | Variable names are bound to objects at runtime without explicit static type declarations. | Reduces boilerplate while preserving strong runtime type safety. |
| Cross-Platform Portability | Standard Python code runs identically across Windows, Linux, and macOS interpreters. | Supports write-once, run-anywhere deployment for scripts and packages. |
| Batteries-Included Library | Ships with a comprehensive standard library covering math, files, regex, networking, and SQLite. | Minimizes external dependencies for everyday engineering tasks. |
| Multi-Paradigm Support | Supports procedural, object-oriented, and functional programming styles seamlessly. | Allows choosing the cleanest abstraction for each problem domain. |
| Automatic Memory Management | Combines reference counting with a cyclic garbage collector to reclaim unused objects. | Prevents manual pointer leaks and dangling memory references. |
2.2 The Python Interpreter: Bytecode and the PVM
Unlike C or C++, which compile source files directly into platform-specific machine instructions, CPython (the reference Python implementation) operates through a two-stage internal pipeline. First, the lexer and parser verify grammatical correctness and construct an Abstract Syntax Tree (AST). Second, the compiler translates the AST into platform-independent bytecode instructions (stored as .pyc files inside __pycache__ directories when modules are imported). Finally, the Python Virtual Machine (PVM) iterates through the bytecode stream inside an evaluation loop, executing each opcode against Python objects in heap memory.
2.3 Interactive Mode vs. Script Mode
Python provides two primary execution environments tailored to different workflows: Interactive Mode and Script Mode.
- Interactive Mode (REPL): Invoked by typing
pythonorpython3in a terminal without a filename, the Read-Eval-Print Loop displays the primary prompt (>>>) and secondary continuation prompt (...). Each statement is read, evaluated immediately by the interpreter, and any resulting expression value is printed directly to standard output. Interactive mode is ideal for testing expressions, inspecting library functions withhelp()ordir(), and performing quick calculations, though entered statements are discarded once the session exits. - Script Mode: Program statements are saved in a plain-text source file bearing the
.pyextension (for example,analytics.py) and executed from the command line viapython analytics.py. In script mode, Python executes statements sequentially from top to bottom and only produces console output when explicit output functions such asprint()are invoked. Script mode is mandatory for production software, multi-module applications, and reproducible academic assignments.
Chapter 3: Lexical Elements, Operators, I/O, and Mutability
3.1 Identifiers and Reserved Keywords
An identifier is the symbolic name assigned by a programmer to a variable, function, class, module, or other program entity. Python enforces strict lexical rules for identifiers: an identifier must begin with an ASCII letter (A-Z, a-z) or an underscore (_), followed by zero or more letters, underscores, or digits (0-9). Identifiers are case-sensitive—meaning totalScore, TotalScore, and totalscore refer to three distinct bindings—and may not contain spaces or punctuation such as @, $, or %. By PEP 8 convention, variable and function names use snake_case, constants use UPPER_SNAKE_CASE, and class names use PascalCase.
Reserved keywords are words permanently claimed by Python's grammar to denote control structures, literal values, and logical operators. Keywords cannot be used as identifiers; attempting to assign to a keyword triggers a SyntaxError. In Python 3, there are 35 reserved keywords including False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, and yield. Notice that True, False, and None are capitalized, whereas all other keywords are lowercase.
3.2 Comments in Python
Comments are non-executable annotations embedded inside source code to clarify intent, document algorithmic invariants, or temporarily disable statements during debugging. Single-line comments begin with the hash character (#) and extend to the end of the physical line. Python does not possess a dedicated multi-line comment delimiter; instead, developers either prefix consecutive lines with # or place triple-quoted string literals ("""...""") immediately after a module, class, or function header as docstrings, which Python preserves in the object's __doc__ attribute for automated documentation tools.
3.3 Operators and Precedence
Operators are special symbols or keywords that perform computations on one or more operands. Python organizes operators into seven principal categories: arithmetic, relational (comparison), logical, assignment, bitwise, membership, and identity operators.
| Category | Operators | Key Semantics | Example |
|---|---|---|---|
| Arithmetic | +, -, *, /, //, %, ** |
/ always yields float; // performs floor division; ** is exponentiation. |
7 // 2 == 3, 2 ** 3 == 8 |
| Comparison | ==, !=, <, >, <=, >= |
Evaluates value relationships and returns Boolean True or False. |
10 <= x <= 20 (chained) |
| Logical | and, or, not |
Combines predicates using short-circuit evaluation. | age >= 18 and has_id |
| Assignment | =, +=, -=, *=, /=, //=, %=, **= |
Binds names or performs augmented in-place updates. | count += 1 |
| Bitwise | &, |, ^, ~, <<, >> |
Manipulates individual binary bits of integer operands. | 5 & 3 == 1, 1 << 3 == 8 |
| Membership | in, not in |
Tests whether an element exists inside a sequence, set, or dictionary keys. | 'py' in 'python' |
| Identity | is, is not |
Tests whether two references point to the exact same object in memory (id()). |
x is None |
When multiple operators appear in a single expression, Python evaluates them according to operator precedence—from parentheses () and exponentiation ** (right-associative) down through unary signs, multiplicative operators (*, /, //, %), additive operators (+, -), bitwise shifts, comparisons, membership/identity, logical not, and, and finally or. Explicit parentheses should always be used in complex expressions to eliminate ambiguity.
3.4 Standard Input and Output
Console interaction in Python relies on the built-in input() and print() functions. Calling input(prompt) displays the optional prompt string, pauses execution until the user presses Enter, and always returns the entered text as a str object. Consequently, numeric inputs must be explicitly converted using constructors such as int() or float() before arithmetic operations are attempted.
The print(*objects, sep=' ', end='\n') function converts each argument to its string representation, separates multiple items using sep (defaulting to a single space), and appends end (defaulting to a newline character). Customizing sep and end allows formatted tabular output or single-line progress updates without extra string concatenation.
3.5 Mutable and Immutable Types
Every value in Python is an object stored in memory with three fundamental attributes: an identity (memory address returned by id()), a type (returned by type()), and a value. If an object's internal state can be altered after creation while preserving its original memory identity, the type is mutable (such as list, dict, and set). Conversely, if any apparent modification actually allocates a brand-new object at a different memory address and rebinds the variable name, the type is immutable (such as int, float, complex, bool, str, and tuple). Understanding mutability prevents subtle aliasing bugs when multiple variables reference the same container.
Chapter 4: Numeric Data Types and String Processing
4.1 Numeric Types: int, float, and complex
Python natively supports three distinct numeric types: arbitrary-precision integers (int), double-precision floating-point numbers (float), and complex numbers (complex).
- Integers (
int): Represent whole numbers of unlimited magnitude, constrained only by available system memory. Integers may be written in decimal (42), binary (0b101010), octal (0o52), or hexadecimal (0x2A) notation, with optional underscores (1_000_000) for visual grouping. - Floating-Point Numbers (
float): Implement IEEE 754 64-bit double-precision binary floating-point arithmetic, offering roughly 15 to 17 significant decimal digits. They support decimal notation (3.14159) and scientific notation (6.022e23). Because binary fractions cannot represent every decimal fraction exactly (for instance,0.1 + 0.2yields0.30000000000000004), floating-point equality checks should use a tolerance viamath.isclose(). - Complex Numbers (
complex): Represent numbers of the form , where is the real part and is the imaginary part (Python usesjrather thani). Both components are stored internally asfloatvalues and accessed through the.realand.imagattributes, while.conjugate()returns .
complex number, , , and is its Euclidean magnitude computed by the built-in abs(z) function.a = 10_000_000_000_000_000_000 + 7 # Arbitrary-precision int
b = 3.5e-2 # Float: 0.035
z1 = complex(3, 4) # 3 + 4j
z2 = 1 - 2j
print("Big int:", a, type(a))
print("Product:", z1 * z2) # (11-2j)
print("Magnitude of z1:", abs(z1)) # 5.0
print("Conjugate of z1:", z1.conjugate())4.2 Strings, Escape Characters, and Indexing
A Python string (str) is an immutable sequence of Unicode code points enclosed in matching single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' / """...""") for multi-line text. Individual characters are accessed via zero-based positive indexing (s[0] for the first character) or negative indexing from the end (s[-1] for the last character). Slicing syntax s[start:stop:step] extracts substrings without mutating the original string.
Escape characters begin with a backslash (\) to encode non-printable control characters or literal quotes inside strings: \n (newline), \t (horizontal tab), \\ (literal backslash), \' (single quote), and \" (double quote). Prefixing a string with r (raw string, such as r"C:\Users\Docs") suppresses escape interpretation, which is especially valuable for Windows file paths and regular expressions.
4.3 String Formatting Functions and Essential Methods
Python offers three mechanisms for embedding expressions and formatting values inside strings: f-strings (formatted string literals introduced in Python 3.6), the str.format() method, and legacy %-formatting. F-strings (f"Score: {score:.2f}") are the modern standard because they evaluate inline expressions directly, execute faster, and support concise format specifiers for alignment (<, >, ^), field width, zero-padding, thousands separators (,), and fixed decimal precision.
Because strings are immutable, string methods never alter the target string in place; instead, they return a newly constructed string or a derived list. Key methods include strip() / lstrip() / rstrip() for trimming whitespace, lower() / upper() / title() for case normalization, find() and index() for substring search, replace(old, new) for substitution, split(sep) for tokenizing into a list, and sep.join(iterable) for concatenating a sequence of strings efficiently.
raw_name = " Ada Lovelace "
clean_name = raw_name.strip().upper()
parts = clean_name.split()
initials = ".".join(p[0] for p in parts) + "."
marks = 94.678
report_f = f"Student: {clean_name:<15} | Initials: {initials} | Score: {marks:06.2f}%"
report_fmt = "Student: {:<15} | Initials: {} | Score: {:06.2f}%".format(clean_name, initials, marks)
print(report_f)
print(report_fmt)
print("Reversed:", clean_name[::-1])4.4 Worked Walkthrough: Parsing and Formatting Structured Student Records
In real-world Python applications, raw textual data arriving from console input, CSV files, or network payloads rarely conforms to clean formatting standards. Consider a university examination cell receiving raw strings formatted as " uk4dsccap203 | ananya menon | 87.456 ". Processing such records safely requires chaining string normalization, splitting, numeric conversion, and precision formatting while avoiding common pitfalls such as mutating strings in place or losing precision during integer truncation.
First, leading and trailing whitespace is stripped with strip(), and the record is partitioned on the delimiter "|" via split("|"). Second, each extracted field is individually trimmed: the course code is normalized to uppercase via upper(), the student name is converted to title case via title(), and the numeric score string is parsed into a float. Third, if grade-point scaling is required, arithmetic expressions convert the raw percentage into a 10-point CGPA using floating-point division, and f-string format specifiers align columns cleanly for console or file output.
records = [
" uk4dsccap203 | ananya menon | 87.456 ",
" uk4dsccap203 | bipin kumar | 74.2 ",
" uk4dsccap203 | chitra nair | 93.812 "
]
header = f"{'Code':<14} {'Student Name':<18} {'Marks':>8} {'Grade Pt':>10}"
print(header)
print("-" * len(header))
for raw in records:
parts = [field.strip() for field in raw.split("|")]
code = parts[0].upper()
name = parts[1].title()
marks = float(parts[2])
grade_pt = marks / 10.0
print(f"{code:<14} {name:<18} {marks:>8.2f} {grade_pt:>10.2f}")4.5 Memory Model, Reference Counting, and Object Identity
Every value manipulated in Python—whether a small integer, a complex number, or a multi-megabyte string—resides as a heap-allocated object managed by the CPython runtime. Variable names do not act as typed memory boxes containing raw bytes; instead, they function as symbolic labels bound to object references. Assigning x = 2500 creates an integer object in heap memory and binds the name x to its address. Executing y = x does not duplicate the integer; it increments the object's reference count and binds y to the exact same address, which can be verified using id(x) == id(y) or the identity operator x is y.
When a variable is reassigned (for example, x = x + 1), Python evaluates 2500 + 1 to allocate a new integer object 2501, decrements the reference count of 2500, and rebinds x to the new object while y continues referencing 2500. For performance optimization, CPython pre-allocates and interns small integers in the range [-5, 256] as well as short identifier-like strings at startup, meaning two variables assigned 42 independently share the same underlying object identity. However, programmers must always use == to compare values and reserve is strictly for singleton checks such as val is None.
| Expression | Value Equality (==) |
Identity Equality (is) |
Underlying Runtime Explanation |
|---|---|---|---|
a = 10; b = 10 |
True |
True (CPython) |
Small integer interning caches integers from -5 to 256. |
a = 10000; b = 10000 |
True |
False (separate runtime objects) |
Large integers allocated dynamically may occupy distinct addresses. |
s1 = "bca"; s2 = "bca" |
True |
True (interned literal) |
Identifier-like compile-time string literals are interned. |
x = [1, 2]; y = [1, 2] |
True |
False |
Mutable containers always allocate distinct heap objects per literal. |
x = [1, 2]; y = x |
True |
True |
Direct assignment creates an alias pointing to the identical list object. |
4.6 Algorithmic Design Case Study: Flowchart, Pseudocode, and Python Trace
To unify problem identification, pseudocode design, operators, and numeric types, consider the computational problem of computing the roots of a quadratic equation with real coefficients where . The discriminant determines whether the equation yields two distinct real roots, one repeated real root, or a pair of complex conjugate roots. By leveraging Python's native complex arithmetic when , a single program handles all mathematical regimes without failing on negative square roots.
import cmath
import math
a = 1.0
b = 2.0
c = 5.0
if a == 0:
print("Coefficient 'a' must be non-zero for a quadratic equation.")
else:
discriminant = b ** 2 - 4 * a * c
if discriminant >= 0:
sqrt_d = math.sqrt(discriminant)
r1 = (-b + sqrt_d) / (2 * a)
r2 = (-b - sqrt_d) / (2 * a)
print(f"Real roots: r1 = {r1:.4f}, r2 = {r2:.4f}")
else:
sqrt_d = cmath.sqrt(discriminant)
r1 = (-b + sqrt_d) / (2 * a)
r2 = (-b - sqrt_d) / (2 * a)
print(f"Complex roots: r1 = {r1}, r2 = {r2}")4.7 Complete Operator Precedence, Associativity, and Short-Circuit Evaluation
Understanding exact operator precedence and associativity prevents subtle logic errors in mathematical and conditional expressions. Python evaluates operators in strict descending precedence tiers. Operators sharing the same precedence level generally associate left-to-right, with the notable exception of exponentiation (**), which associates right-to-left (so 2 ** 3 ** 2 evaluates as 2 ** (3 ** 2) = 512 rather than 64), and chained comparisons (a < b < c), which expand logically to (a < b) and (b < c) with the middle operand evaluated only once.
| Precedence Tier | Operators | Associativity | Evaluation Example |
|---|---|---|---|
| 1 (Highest) | () (Parentheses), x[i], x.attr, f(args) |
Left-to-right | (2 + 3) * 4 == 20 |
| 2 | ** (Exponentiation) |
Right-to-left | 2 ** 3 ** 2 == 512 |
| 3 | +x, -x, ~x (Unary sign & bitwise NOT) |
Right-to-left | -3 ** 2 == -9 (** binds tighter than unary -) |
| 4 | *, /, //, % |
Left-to-right | 17 // 5 * 2 == 6 |
| 5 | +, - (Binary addition/subtraction) |
Left-to-right | 10 - 3 + 2 == 9 |
| 6 | <<, >> (Bitwise shifts) |
Left-to-right | 1 << 4 == 16 |
| 7–9 | &, then ^, then | (Bitwise logic) |
Left-to-right | 6 & 3 == 2 |
| 10 | ==, !=, <, <=, >, >=, in, is |
Chained | 1 < 5 < 10 == True |
| 11–13 (Lowest) | not, then and, then or |
Left-to-right | not False and True == True |
Logical operators and and or implement short-circuit evaluation and return one of their actual operands rather than strictly coercing to bool. In A and B, if A is falsy, Python immediately returns A without evaluating B; otherwise it evaluates and returns B. In A or B, if A is truthy, Python immediately returns A without evaluating B; otherwise it evaluates and returns B. This behavior allows safe guard idioms such as if divisor != 0 and total / divisor > 10: and fallback defaults such as display_name = user_input or "Guest".
4.8 Unicode Strings, Encoding, and Immutability in Practice
In Python 3, every str object stores an immutable sequence of abstract Unicode code points (supporting Latin, Malayalam, Hindi, mathematical symbols, and emojis natively). When strings must be transmitted over networks or written to binary files, they are encoded into raw bytes using a character encoding such as UTF-8 via text.encode("utf-8"), and reconstructed via raw_bytes.decode("utf-8"). Calling ord(ch) returns the integer Unicode code point of a single character, while chr(code) performs the inverse mapping—essential for implementing character ciphers, input validation, and lexical scanners.
READ_PERM = 0b001
WRITE_PERM = 0b010
EXEC_PERM = 0b100
user_perm = READ_PERM | WRITE_PERM
print("Can write?", bool(user_perm & WRITE_PERM))
print("Can exec? ", bool(user_perm & EXEC_PERM))
# Unicode code points and UTF-8 byte length
label = "Python 3"
codes = [ord(c) for c in label]
utf8_bytes = label.encode("utf-8")
print("Code points:", codes)
print("UTF-8 bytes:", utf8_bytes, "| Byte count:", len(utf8_bytes))Module II: Data Structures & Type Conversion
Chapter 5: Lists and Tuples in Python
5.1 Python Lists: Creation, Indexing, and Slicing
A list is an ordered, mutable, heterogeneous sequence capable of storing elements of any data type—including integers, strings, nested lists, or custom objects—within square brackets ([10, "BCA", 3.14]). Because lists maintain insertion order and allow duplicate values, they serve as Python's primary general-purpose dynamic array. Internally, CPython implements lists as contiguous arrays of object pointers that automatically over-allocate capacity during growth, ensuring amortized append performance.
Elements are retrieved using zero-based indices (L[0]) or negative indices (L[-1]). Slicing (L[start:stop:step]) returns a shallow copy of the selected subsequence. Lists also support slice assignment (L[1:3] = [20, 30, 40]), allowing contiguous segments to be replaced, inserted, or deleted in place.
5.2 Built-in List Functions and Methods
Python provides both global built-in functions that operate on lists (such as len(), sum(), min(), max(), sorted(), any(), all(), and enumerate()) and mutating/querying list methods invoked directly on a list instance.
| List Method | Operation Performed | Return Value | Time Complexity |
|---|---|---|---|
append(x) |
Adds a single element x to the end of the list. |
None (in-place) |
amortized |
extend(iterable) |
Appends all items from another iterable to the list. | None (in-place) |
|
insert(i, x) |
Inserts element x at index i, shifting subsequent items right. |
None (in-place) |
|
remove(x) |
Deletes the first occurrence of value x; raises ValueError if absent. |
None (in-place) |
|
pop([i]) |
Removes and returns element at index i (defaults to last element). |
Removed element | at end, middle |
sort(key=..., reverse=...) |
Sorts the list in place using Timsort (stable hybrid merge/insertion sort). | None (in-place) |
|
reverse() |
Reverses the element order of the list in place. | None (in-place) |
|
index(x) / count(x) |
Finds first index of x / counts occurrences of x. |
int |
|
copy() / clear() |
Returns a shallow copy / removes all elements from the list. | New list / None |
/ |
scores = [78, 92, 65, 88, 92]
scores.append(81)
scores.insert(1, 95)
top_score = scores.pop(1)
print("Popped:", top_score, "| Count of 92:", scores.count(92))
# sorted() returns a new list; list.sort() mutates in place
ordered = sorted(scores, reverse=True)
print("Original:", scores)
print("Descending:", ordered)
# Shallow copy prevents aliasing on top-level mutations
backup = scores.copy()
backup.clear()
print("After clearing backup, original remains:", scores)5.3 Tuples: Immutability, Packing, and Built-in Functions
A tuple is an ordered, immutable sequence written with parentheses—for example, (10, 20, 30)—or simply comma-separated values. Because a single-element expression like (42) is parsed as a parenthesized integer, a trailing comma is mandatory for a one-element tuple: (42,). Tuples support indexing, slicing, concatenation (+), repetition (*), and membership testing (in), but lack mutating methods such as append() or sort().
Tuples are used extensively for heterogeneous records (such as database rows or coordinate pairs), multiple return values from functions, and dictionary keys (provided all nested elements are also immutable). Python supports automatic tuple packing (point = 12, 45) and tuple unpacking (x, y = point), including extended star-unpacking (head, *middle, tail = [1, 2, 3, 4, 5]). Built-in tuple functions include len(), min(), max(), sum(), sorted() (which returns a sorted list), tuple(), and the two tuple methods count(x) and index(x).
Chapter 6: Sets and Dictionaries
6.1 Sets: Unordered Collections and Mathematical Operations
A set is an unordered, mutable collection of unique, hashable elements enclosed in curly braces ({1, 2, 3}). Because an empty pair of braces {} creates an empty dictionary, an empty set must be constructed using set(). Sets automatically eliminate duplicate entries and use a hash table internally, enabling average membership testing (x in s)—vastly faster than linear scanning in large lists.
Python sets directly model mathematical set theory, supporting both symbolic operators and named methods for union, intersection, difference, and symmetric difference.
A | B (A.union(B)), corresponds to A & B (A.intersection(B)), corresponds to A - B (A.difference(B)), and corresponds to A ^ B (A.symmetric_difference(B)).Essential mutating and relational set methods include add(x), update(iter), remove(x) (raises KeyError if missing), discard(x) (safe removal without error if missing), pop(), clear(), issubset() (<=), issuperset() (>=), and isdisjoint(). When an immutable set is required—for example, as a dictionary key—Python provides frozenset().
lab_a = {"UK401", "UK402", "UK403", "UK404"}
lab_b = {"UK403", "UK404", "UK405"}
print("All enrolled:", lab_a | lab_b)
print("Both labs:", lab_a & lab_b)
print("Only Lab A:", lab_a - lab_b)
print("Exclusive to one lab:", lab_a ^ lab_b)
lab_a.discard("UK999") # No error if absent
lab_a.add("UK406")
print("Updated Lab A:", sorted(lab_a))6.2 Dictionaries: Key-Value Mapping Architecture
A dict (dictionary) is a mutable, insertion-ordered mapping that associates unique, immutable (hashable) keys with arbitrary values: {"code": "UK4DSCCAP203", "credits": 4}. Like sets, dictionaries rely on open-addressed hash tables, delivering average lookup, insertion, and deletion by key. Keys must be hashable (strings, numbers, or tuples of immutable objects), whereas values can be any Python object including lists or nested dictionaries.
| Dictionary Method / Function | Behavior | Safety / Edge Case Note |
|---|---|---|
d.get(k, default=None) |
Returns value for key k if present, else returns default. |
Avoids KeyError raised by d[k]. |
d.keys() / d.values() / d.items() |
Returns dynamic view objects of keys, values, or (key, value) pairs. |
Views reflect subsequent mutations automatically. |
d.update(other) |
Merges key-value pairs from other, overwriting existing keys. |
Supports dict or iterable of pairs; Python 3.9+ also supports d1 | d2. |
d.pop(k, default) |
Removes key k and returns its value. |
Raises KeyError if absent unless default is given. |
d.popitem() |
Removes and returns the most recently inserted (key, value) tuple. |
Follows LIFO order in Python 3.7+; raises KeyError if empty. |
d.setdefault(k, default) |
Returns d[k] if present; otherwise inserts d[k] = default and returns it. |
Useful for initializing grouped lists or counters. |
dict.fromkeys(keys, val) |
Class method creating a new dictionary with shared initial value val. |
Avoid mutable objects for val to prevent shared aliasing. |
words = ["python", "list", "python", "tuple", "set", "python", "set"]
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
for word, count in freq.items():
print(f"{word:<8} -> {count}")
student = {
"id": "BCA2401",
"marks": {"python": 91, "security": 85}
}
print("Python marks:", student.get("marks", {}).get("python", 0))Chapter 7: Mutability, Memory Identity, and Type Conversion
7.1 Comparing Mutable and Immutable Containers
Choosing between lists, tuples, sets, and dictionaries depends on whether order, uniqueness, key-value association, or mutability is required. Mutability directly affects function parameter passing and variable assignment. In Python, assignment (b = a) never copies data; it binds a second name to the identical object reference. When a is a mutable list, mutating b.append(99) mutates the shared object visible through a. When a is an immutable tuple or string, operations such as a += (99,) create a new object and rebind only a, leaving b untouched.
| Type | Ordered | Mutable | Allows Duplicates | Hashable | Primary Use Case |
|---|---|---|---|---|---|
list |
Yes | Yes | Yes | No | Dynamic sequences, stacks, queues, homogeneous collections. |
tuple |
Yes | No | Yes | If elements hashable | Fixed records, function return tuples, dictionary keys. |
set |
No | Yes | No | No | Deduplication, fast membership tests, set algebra. |
dict |
Yes (insertion) | Yes | Keys: No; Values: Yes | No | Indexed lookup tables, JSON-like records, caches. |
7.2 Implicit and Explicit Data Type Conversion
Python performs implicit type conversion (coercion) only in safe, lossless numeric contexts—for example, adding an int and a float promotes the integer to float (5 + 2.5 == 7.5), and adding a float and a complex promotes to complex. Unlike weakly typed languages, Python refuses to implicitly concatenate strings and integers ("Age: " + 20 raises TypeError), preventing silent coercion defects.
Explicit type conversion (type casting) invokes built-in constructors: int(x, base), float(x), complex(a, b), bool(x), str(x), list(iter), tuple(iter), set(iter), and dict(pairs). Truthiness conversion via bool(x) treats zero numeric values (0, 0.0, 0j), None, and empty containers ("", [], (), set(), {}) as False, while all non-zero numbers and non-empty containers evaluate to True.
hex_str = "1F"
decimal_val = int(hex_str, 16) # Base-16 conversion -> 31
pairs = [("a", 1), ("b", 2), ("a", 1)]
unique_pairs = set(pairs) # Deduplicate tuples
lookup = dict(unique_pairs) # Convert pairs to dict
keys_list = list(lookup.keys()) # Extract keys as list
print("Decimal:", decimal_val)
print("Dict:", lookup, "| Keys:", keys_list)
print("Truthiness of empty list:", bool([]), "| Non-empty:", bool([0]))7.3 Shallow Copy vs. Deep Copy and Aliasing Hazards
When working with nested mutable structures—such as a list of lists or a dictionary containing list values—understanding the distinction between assignment, shallow copying, and deep copying is essential to prevent unintended data corruption. Direct assignment (b = a) creates an alias: both variables point to the identical outer container object. Calling b = a.copy() or slicing b = a[:] creates a shallow copy: Python allocates a new outer list object, but fills it with references to the exact same inner objects. Consequently, appending a new row to b does not affect a, yet mutating an inner nested list via b[0].append(99) immediately mutates a[0] as well.
To achieve complete structural isolation across arbitrary nesting depths, Python's standard copy module provides copy.deepcopy(a), which recursively duplicates the outer container along with every nested mutable object inside it. While deep copying guarantees zero shared mutable state, it consumes additional memory and CPU time proportional to the total object graph size.
import copy
original = [[10, 20], [30, 40]]
alias = original
shallow = original.copy()
deep = copy.deepcopy(original)
shallow[0].append(999) # Mutates shared inner list [10, 20]
deep[1].append(777) # Mutates only deep copy's inner list
print("Original:", original) # [[10, 20, 999], [30, 40]]
print("Alias: ", alias) # [[10, 20, 999], [30, 40]]
print("Shallow: ", shallow) # [[10, 20, 999], [30, 40]]
print("Deep: ", deep) # [[10, 20], [30, 40, 777]]7.4 Built-in Sequence Utilities: enumerate, zip, reversed, and sorted
Python provides high-level built-in functions that operate uniformly across lists, tuples, sets, and dictionary views without requiring manual index counters:
enumerate(iterable, start=0): Yields(index, element)tuples lazily, eliminating error-pronerange(len(seq))loops when both element position and value are needed.zip(*iterables): Pairs corresponding elements from two or more iterables into tuples, stopping automatically when the shortest iterable is exhausted. Pairingdict(zip(keys, values))is the idiomatic way to construct a dictionary from parallel lists.reversed(sequence): Returns a reverse iterator over a sequence in extra memory without copying or mutating the original container.sorted(iterable, key=None, reverse=False): Accepts any iterable (including tuples, sets, and dictionaries) and returns a newly allocated sortedlist. Supplying akeyfunction (such askey=lenorkey=str.lower) customizes ordering without modifying elements.all(iterable)andany(iterable): Perform short-circuit Boolean reductions—all()returnsTrueif every element is truthy (or the iterable is empty), whileany()returnsTrueas soon as at least one truthy element is encountered.
7.5 Tuple Immutability Nuances and Hashability
Although a tuple itself cannot be resized or have its top-level element references rebound, a tuple can legally hold references to mutable objects such as lists: record = ("BCA", [80, 90]). In this case, record[1].append(95) succeeds because the tuple's slot still points to the identical list object. However, such a tuple is not hashable: calling hash(record) or attempting to use record as a dictionary key or set element raises TypeError: unhashable type: 'list'. A tuple is hashable only when all of its elements—recursively—are immutable and hashable.
7.6 Comprehensive Type Conversion Matrix and Worked Application
Real-world Python data pipelines continuously convert between containers to exploit each structure's algorithmic strengths: converting a list to a set to remove duplicates in average time, converting a dictionary's .items() to a sorted list of tuples for ranking, or converting strings to lists of characters for in-place edits before joining back.
| Source → Target | Python Expression | Conversion Semantics | Information Loss / Constraint |
|---|---|---|---|
list → set |
set(my_list) |
Removes duplicates; enables membership tests. | Original ordering is discarded; elements must be hashable. |
list → tuple |
tuple(my_list) |
Freezes sequence into an immutable record. | Zero loss; enables hashing if elements are immutable. |
str → list |
list(text) / text.split() |
Splits into characters or whitespace-delimited tokens. | Zero loss; enables mutating operations. |
dict → list |
list(d) / list(d.items()) |
Extracts keys or (key, value) pairs in insertion order. |
list(d) retains keys only; use .items() for both. |
zip → dict |
dict(zip(keys, vals)) |
Builds key-value mapping from parallel sequences. | Truncates to shorter sequence; duplicate keys overwrite. |
# Attendance sets for two lab sessions
lab_python = {"BCA101", "BCA102", "BCA103", "BCA104"}
lab_dbms = {"BCA102", "BCA104", "BCA105"}
both_labs = lab_python & lab_dbms
only_one = lab_python ^ lab_dbms
print("Attended both:", sorted(both_labs))
print("Attended exactly one:", sorted(only_one))
# Gradebook using dictionary of tuples
gradebook = {
"BCA101": ("Ananya", [88, 92, 85]),
"BCA102": ("Bipin", [76, 81, 79]),
"BCA103": ("Chitra", [94, 90, 96]),
}
averages = []
for roll, (name, marks) in gradebook.items():
avg = sum(marks) / len(marks)
averages.append((avg, roll, name))
# Rank students descending by average score
for rank, (avg, roll, name) in enumerate(sorted(averages, reverse=True), start=1):
print(f"Rank {rank}: {roll} - {name:<8} | Average: {avg:.2f}")7.7 Using Lists as Stacks and Queues: Algorithmic Trade-Offs
Because Python lists provide amortized append and pop at the right end, a standard list serves directly as an efficient Last-In, First-Out (LIFO) stack using stack.append(item) to push and stack.pop() to pop. Stacks underlie expression evaluation, balanced parenthesis checking, undo-redo histories, and depth-first traversal.
By contrast, using a standard list as a First-In, First-Out (FIFO) queue via queue.pop(0) or queue.insert(0, item) degrades to per operation because every remaining pointer in the contiguous array must shift left or right by one slot. For high-throughput queues, Python's standard collections.deque (double-ended queue) uses a doubly-linked block list that guarantees performance for both append() and popleft().
def is_balanced(expr):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in expr:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return len(stack) == 0
samples = ["{[a + (b * c)]}", "([)]", "((x + y))"]
for s in samples:
print(f"{s:<18} -> Balanced: {is_balanced(s)}")7.8 Advanced Dictionary Patterns: Comprehensions, Grouping, and Merging
Dictionary comprehensions construct mappings declaratively using curly braces with key-value pairs: {k: v for item in iterable if cond}. They are particularly effective for inverting one-to-one mappings, filtering configuration dictionaries, and normalizing keys. When grouping records by category (such as grouping students by semester or words by initial letter), dict.setdefault(key, []) initializes an empty bucket only on first encounter, avoiding verbose if key not in d: checks.
Sorting a dictionary by its values requires extracting d.items() and passing a key function to sorted(), producing an ordered list of (key, value) tuples (or rebuilding a sorted dictionary from those pairs). In Python 3.9+, two dictionaries are merged cleanly into a new dictionary using the union operator merged = defaults | overrides, where keys in overrides take precedence, or updated in place via defaults |= overrides.
catalog = {
"UK4DSCCAP203": 4,
"UK4DSCCAP204": 4,
"UK4SECCAP201": 3,
"UK4VAC202": 2
}
# Dictionary comprehension: filter 4-credit courses
core_courses = {code: cr for code, cr in catalog.items() if cr >= 4}
# Grouping courses by credit count
by_credits = {}
for code, cr in catalog.items():
by_credits.setdefault(cr, []).append(code)
# Sorting by value ascending, then code alphabetically
ranked = sorted(catalog.items(), key=lambda pair: (pair[1], pair[0]))
print("Core courses:", core_courses)
print("Grouped by credits:", by_credits)
print("Sorted entries:", ranked)7.9 Set Theory in Practice: Frozensets, Role Permissions, and Deduplication
Because standard set objects are mutable, they cannot be hashed and therefore cannot serve as elements inside another set or as keys in a dictionary. When a collection of unique items must itself act as a dictionary key—such as caching results for an unordered pair of nodes or indexing permission bundles—Python provides the immutable frozenset(iterable) type. A frozenset supports all non-mutating set operations (union, intersection, difference, subset testing) while remaining hashable.
In addition, Python 3.7+ preserves insertion order in dictionaries, allowing order-preserving deduplication of a list in time via list(dict.fromkeys(items))—combining the uniqueness guarantee of hash tables with the original sequence ordering that list(set(items)) would scramble.
7.10 Mutable Default Argument Trap and Safe Patterns
One of the most famous mutability pitfalls in Python occurs when a mutable object (such as [] or {}) is used as a default parameter value in a function definition: def add_tag(tag, tags=[]):. Python evaluates default argument expressions only once at function definition time (def), not on each function call. Consequently, every call that omits tags mutates the exact same shared list across the lifetime of the program. The universal remedy is to use None as the immutable sentinel default and allocate a fresh container inside the function body whenever the argument is None.
def append_log(entry, history=None):
if history is None:
history = []
history.append(entry)
return history
log_a = append_log("Boot")
log_b = append_log("Login")
print("Log A:", log_a) # ['Boot']
print("Log B:", log_b) # ['Login']
# Order-preserving deduplication using dict.fromkeys
raw_tags = ["python", "oop", "python", "sql", "oop", "regex"]
unique_ordered = list(dict.fromkeys(raw_tags))
print("Unique ordered tags:", unique_ordered)7.11 Worked Case Study: Multi-Container E-Commerce Inventory & Cart Engine
To synthesize lists, tuples, sets, dictionaries, and type conversions in a cohesive application, consider an inventory and shopping cart processor. Product catalog entries are stored in a dictionary mapping SKU strings to immutable (name, unit_price, stock) tuples. Customer cart actions arrive as a list of (sku, quantity) tuples, while promotional discount eligibility is checked in time using a set of eligible SKUs. During checkout, tuple unpacking, dictionary lookups, safe defaults via get(), and explicit numeric conversions compute itemized totals and remaining stock cleanly.
inventory = {
"P101": ("USB-C Hub", 1250.0, 15),
"P102": ("Mechanical Keyboard", 3400.0, 8),
"P103": ("Laptop Stand", 890.0, 20),
}
promo_skus = {"P101", "P103"}
cart = [("P101", 2), ("P102", 1), ("P101", 1)]
aggregated = {}
for sku, qty in cart:
aggregated[sku] = aggregated.get(sku, 0) + qty
grand_total = 0.0
for sku, qty in aggregated.items():
name, price, stock = inventory[sku]
if qty > stock:
print(f"Insufficient stock for {name}")
continue
discount = 0.10 if sku in promo_skus else 0.0
line_total = qty * price * (1.0 - discount)
grand_total += line_total
inventory[sku] = (name, price, stock - qty)
print(f"{name:<20} x{qty} -> Rs. {line_total:,.2f}")
print(f"Grand Total: Rs. {grand_total:,.2f}")7.12 Hash Table Mechanics, Load Factor, and Key Selection Rules
Both set and dict achieve near-constant average lookup speed through open-addressed hash tables. When a key is inserted, Python computes its integer hash digest via hash(key) and maps that digest to a slot index using bit-masking over the table capacity. If two distinct keys map to the same slot (a hash collision), CPython probes subsequent pseudo-random slots until an empty slot or matching key is found. Whenever the table's load factor exceeds two-thirds of its allocated slots, Python automatically resizes the table and rehashes existing entries.
This internal architecture explains two strict rules for dictionary keys and set elements. First, keys must be hashable—meaning their hash value never changes during their lifetime and they implement equality comparison (__eq__). Consequently, immutable primitives (int, float, str, bool, None), frozenset, and tuples containing only hashable elements are valid keys, whereas mutable list, set, and dict objects raise TypeError: unhashable type. Second, numeric keys that compare equal must hash identically: in Python, 1 == 1.0 == True and hash(1) == hash(1.0) == hash(True), so inserting {1: "int", True: "bool"} overwrites the single key 1 with value "bool" while retaining the first inserted key object.
7.13 Extended Star Unpacking and Structural Data Normalization
When processing variable-length records represented as lists or tuples, Python's extended iterable unpacking (using a single starred target *rest) binds zero or more elements into a list while unpacking fixed-position fields into named variables. For instance, given a CSV row ["BCA2401", "Ananya", 88, 91, 85, 90], writing roll, name, *marks = row cleanly isolates the identifier, student name, and arbitrary-length list of subject scores in one readable statement. Similarly, first, *middle, last = sorted_scores extracts boundary values without brittle slice indices.
records = [
("UK401", "Arjun", 78, 84, 91),
("UK402", "Bhavna", 92, 89, 95, 88),
]
for roll, name, *scores in records:
avg = sum(scores) / len(scores)
print(f"{roll} | {name:<8} | Exams: {len(scores)} | Avg: {avg:.2f}")
# Numeric key equivalence in dictionaries
d = {}
d[1] = "integer one"
d[1.0] = "float one"
d[True] = "boolean true"
print("Dictionary after 1, 1.0, True insertions:", d)7.14 Memory Footprint Comparison and Container Selection Guide
Choosing the optimal built-in container impacts both execution speed and memory consumption in large-scale Python programs. A tuple occupies slightly less memory than an equivalent list because tuples are fixed-length and do not over-allocate growth buffers. Meanwhile, set and dict allocate sparse hash tables with roughly one-third empty slots to maintain probe chains, trading higher memory per element for instantaneous lookup. Programmers should default to tuples for fixed heterogeneous records, lists for ordered dynamic sequences, sets for deduplication and membership checks, and dictionaries for key-indexed mappings.
import sys
sample_list = [1, 2, 3, 4, 5]
sample_tuple = (1, 2, 3, 4, 5)
sample_set = {1, 2, 3, 4, 5}
sample_dict = {i: i * 10 for i in range(1, 6)}
print("List bytes: ", sys.getsizeof(sample_list))
print("Tuple bytes:", sys.getsizeof(sample_tuple))
print("Set bytes: ", sys.getsizeof(sample_set))
print("Dict bytes: ", sys.getsizeof(sample_dict))7.15 Dictionary View Objects and Dynamic Iteration Safety
Calling d.keys(), d.values(), or d.items() does not return static lists; instead, these methods return dynamic dictionary view objects that reflect subsequent insertions and deletions in real time in memory. Because mutating a dictionary's size (inserting or deleting keys) while iterating directly over a view raises RuntimeError: dictionary changed size during iteration, programmers must iterate over a snapshot copy such as list(d.keys()) or build a filtered dictionary via comprehension whenever keys are conditionally removed.
Similarly, removing elements from a list while iterating forward with for x in lst: causes index shifting that skips adjacent items. Safe filtering uses either a list comprehension ([x for x in lst if keep(x)]) or backward index iteration.
scores = {"Ananya": 91, "Bipin": 34, "Chitra": 88, "Deepak": 29}
# Safe removal using a snapshot of keys
for name in list(scores.keys()):
if scores[name] < 40:
del scores[name]
print("Passing students:", scores)
# Safe list filtering using comprehension
raw_vals = [12, -5, 0, 18, -2, 25]
positive_vals = [v for v in raw_vals if v > 0]
print("Positive values:", positive_vals)7.16 Set Comprehensions and Asymmetric Difference Applications
Just like list and dictionary comprehensions, Python supports set comprehensions using curly braces without colons: {expr for item in iterable if cond}. Set comprehensions automatically deduplicate transformed results in a single pass—for example, extracting unique lowercase domain names from a list of email addresses via {email.split("@")[1].lower() for email in emails}. Combined with relational set comparisons (A <= B for subset, A < B for proper subset, and A.isdisjoint(B)), set comprehensions express complex membership invariants concisely and clearly.
Module III: Flow Control & Functions
Chapter 8: Decision Making and Iterative Flow Control
8.1 Conditional Branching: if, if-else, and if-elif-else
Control flow statements determine the runtime execution path of a program based on Boolean conditions. Python uses indentation (four spaces per level by PEP 8 standard) to delimit the body of each branch. The simplest conditional is the if statement, which executes its suite only when its predicate evaluates to truthy. Adding an else clause guarantees mutually exclusive two-way branching, whereas chained elif (else-if) clauses evaluate multiple conditions sequentially from top to bottom and execute only the first matching branch.
For concise single-expression assignments, Python provides the conditional expression (ternary operator): status = "Pass" if marks >= 40 else "Fail". Conditional blocks may also be nested inside one another when decisions depend on hierarchical criteria, though flattening nested checks with elif or logical and/or improves readability.
8.2 Iteration: for, range(), and while Loops
Iteration repeats a block of statements either over a known sequence or until a condition becomes false.
- The
forLoop andrange(): Python'sforstatement is a definite iterator that traverses any iterable object—lists, strings, tuples, dictionaries, sets, or file streams—binding each element in turn to the loop variable. When numeric counting is required, the lazyrange(start, stop, step)object generates integers fromstart(inclusive, default 0) up tostop(exclusive) by increments ofstep(default 1) in memory. - The
whileLoop: An indefinite pretest loop that repeatedly evaluates a condition before each iteration and executes its body while the condition remains truthy. Everywhileloop must update its state toward termination; otherwise, an infinite loop occurs. - Nested Loops: Placing one loop inside another enables multidimensional traversal—such as processing matrices, generating multiplication tables, or comparing pairs of items—with total inner executions equal to the product of outer and inner iteration counts.
8.3 Loop Control: break, continue, pass, and loop-else
Python provides fine-grained loop control keywords and a distinctive else clause attached to loops:
break: Immediately terminates the innermost enclosingfororwhileloop and transfers control to the statement following the loop.continue: Skips the remaining statements in the current iteration and jumps directly to the next iteration check (or next element in aforloop).pass: A null-operation placeholder statement that performs nothing at runtime; it satisfies Python's syntax requirement wherever an indented block is mandatory (such as stub functions or empty exception handlers).- Loop with
else: Bothforandwhileloops accept an optionalelse:suite that executes only if the loop terminates naturally (by exhausting the iterable or when thewhilecondition becomes false) and never executes if the loop was exited viabreak. This construct is uniquely suited for search algorithms where theelsebranch handles the "target not found" outcome cleanly without extra Boolean flag variables.
for num in range(10, 21):
for divisor in range(2, int(num ** 0.5) + 1):
if num % divisor == 0:
print(f"{num} = {divisor} * {num // divisor}")
break
else:
# Runs only when no divisor triggered 'break'
print(f"{num} is prime")Chapter 9: List Comprehensions and Nested Lists
9.1 List Comprehension Syntax and Filtering
A list comprehension is a compact, declarative expression that constructs a new list by applying a transformation—and optional filtering—to every element of an iterable. Its general form is [expression for item in iterable if condition]. Internally, list comprehensions execute the iteration loop in C-level bytecode, making them both more concise and measurably faster than building a list via repeated list.append() calls inside a manual for loop.
Conditional logic inside comprehensions takes two distinct positions: a trailing if clause filters which elements are included, whereas an inline if ... else before the for keyword transforms every element conditionally (for example, ["Even" if x % 2 == 0 else "Odd" for x in range(5)]).
9.2 Nested Lists and Matrix Comprehensions
A nested list is a list whose elements are themselves lists, commonly used to represent two-dimensional matrices, grids, or tabular datasets. Accessing an element in row r and column c uses double indexing: matrix[r][c]. Nested list comprehensions allow both constructing 2D matrices (avoiding the classic [[0]*3]*3 shared-row aliasing bug) and flattening 2D lists into 1D sequences.
# Safe 3x3 identity matrix using nested list comprehension
identity = [[1 if r == c else 0 for c in range(3)] for r in range(3)]
matrix = [
[1, 2, 3],
[4, 5, 6]
]
# Transpose 2x3 matrix to 3x2
transpose = [[row[c] for row in matrix] for c in range(len(matrix[0]))]
# Flatten 2D matrix into 1D list of even squares
even_squares = [val ** 2 for row in matrix for val in row if val % 2 == 0]
print("Identity:", identity)
print("Transpose:", transpose)
print("Even squares:", even_squares)Chapter 10: Functions, Recursion, and Functional Primitives
10.1 Function Definition, Calling, and Return Semantics
A function is a named, reusable block of code that encapsulates a specific task, accepts input parameters, performs computation, and optionally returns a result to its caller. Functions are defined using the def keyword followed by the function name, a parenthesized parameter list, and a colon. Calling a function transfers execution to its body; encountering a return statement immediately exits the function and passes the specified object back to the call site. If a function reaches its end without executing a return expression, Python implicitly returns None. Returning multiple comma-separated values actually packs and returns a single tuple.
10.2 Function Arguments: Positional, Keyword, Default, and Variable-Length
Python supports highly expressive argument-passing rules that must follow a strict parameter ordering in function definitions: standard positional-or-keyword parameters, default-value parameters, arbitrary positional arguments (*args), keyword-only parameters, and arbitrary keyword arguments (**kwargs).
| Argument Form | Syntax in Definition | Runtime Binding Behavior |
|---|---|---|
| Positional | def f(a, b): |
Arguments matched strictly left-to-right by position. |
| Keyword | f(b=20, a=10) |
Arguments matched by parameter name regardless of call order. |
| Default | def f(a, b=10): |
Uses fallback value if caller omits the argument; never use mutable defaults like []. |
| Variable Positional | def f(*args): |
Collects zero or more excess positional arguments into a tuple. |
| Variable Keyword | def f(**kwargs): |
Collects excess keyword arguments into a dict. |
10.3 Anonymous Functions (lambda) and Higher-Order Functions
A lambda expression creates a small, unnamed single-expression function at runtime with syntax lambda params: expression. Unlike def, a lambda body cannot contain statements such as loops or assignments and automatically returns the value of its single expression. Lambdas are primarily used as inline callbacks for sorting keys (sorted(items, key=lambda x: x[1])) and higher-order functional primitives:
map(func, iterable): Lazily appliesfuncto every element ofiterable, yielding a map iterator of transformed results.filter(func, iterable): Lazily yields only those elements ofiterablefor whichfunc(item)returns truthy.functools.reduce(func, iterable[, initial]): Imported from the standardfunctoolsmodule,reducecumulatively applies a two-argument function from left to right, folding the sequence into a single summary value.
10.4 Recursion and Base Cases
Recursion occurs when a function calls itself directly or indirectly to solve smaller instances of the same problem. Every sound recursive function requires two components: at least one base case that returns a result directly without further recursive calls, and a recursive step that reduces the problem size strictly toward the base case. Without a reachable base case, Python halts infinite recursion by raising RecursionError once the call stack reaches sys.getrecursionlimit() (typically 1000 frames).
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
squared_evens = list(map(lambda x: x ** 2, evens))
total = reduce(lambda acc, x: acc + x, squared_evens, 0)
def gcd(a, b):
if b == 0:
return abs(a)
return gcd(b, a % b)
print("Squared evens:", squared_evens, "| Sum:", total)
print("GCD(48, 18):", gcd(48, 18))10.5 Call Stack Mechanics and Memoized Recursion
Every time a function is invoked in Python, the Python Virtual Machine allocates a new stack frame on the call stack to store the function's local variables, parameter bindings, and the return address in the caller. In recursive functions, each nested call pushes another frame onto the stack until the base case is reached, at which point frames unwind in Last-In, First-Out (LIFO) order as return values propagate back to the initial caller.
While recursion expresses divide-and-conquer algorithms—such as binary search, tree traversals, and quicksort—with mathematical clarity, naive recursion can recompute identical subproblems exponentially many times. For example, computing naively invokes over 29 million recursive calls. Memoization eliminates redundant work by caching previously computed results in a dictionary (or via @functools.lru_cache), reducing exponential complexity to linear time.
def binary_search(arr, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, target, low, mid - 1)
else:
return binary_search(arr, target, mid + 1, high)
def fib_memo(n, cache=None):
if cache is None:
cache = {0: 0, 1: 1}
if n not in cache:
cache[n] = fib_memo(n - 1, cache) + fib_memo(n - 2, cache)
return cache[n]
sorted_data = [11, 23, 35, 47, 59, 68, 82]
print("Index of 59:", binary_search(sorted_data, 59, 0, len(sorted_data) - 1))
print("Fibonacci(35):", fib_memo(35))10.6 Comparing List Comprehensions vs. map() and filter()
Both list comprehensions and the functional primitives map() and filter() express element-wise transformations and predicate selection without explicit accumulator boilerplate. Understanding their trade-offs helps programmers choose the clearest idiom:
| Dimension | List Comprehension | map() and filter() |
|---|---|---|
| Evaluation Strategy | Eager: immediately constructs and returns a full list in memory. |
Lazy: returns an iterator yielding elements on demand in memory. |
| Readability with Lambdas | Inline expressions avoid lambda boilerplate cleanly. |
Requires passing an existing function or an inline lambda. |
| Combined Transform + Filter | Single expression: [x*2 for x in nums if x > 0]. |
Requires nesting map(f, filter(p, nums)). |
| Reuse of Existing Functions | Calls [int(s) for s in tokens]. |
Very clean when passing a named function: map(int, tokens). |
10.7 Sentinel-Controlled while Loops and Parameter Passing Semantics
Unlike definite for loops that iterate over pre-existing collections, sentinel-controlled while loops repeat until a special sentinel value (such as "QUIT" or -1) or convergence criterion is encountered. When passing arguments to functions inside loops, Python uses pass-by-object-reference (also called call-by-sharing): the function parameter receives a reference to the caller's object. Rebinding a parameter inside the function never alters the caller's variable, whereas mutating a passed mutable list or dictionary modifies the caller's object directly.
def summarize_scores(student_name, *scores, **metadata):
if not scores:
return f"{student_name}: No scores recorded."
avg = sum(scores) / len(scores)
dept = metadata.get("dept", "BCA")
sem = metadata.get("sem", 4)
return f"{student_name} ({dept} Sem {sem}) -> Avg: {avg:.2f}, Max: {max(scores)}"
print(summarize_scores("Devika", 88, 92, 85, dept="BCA", sem=4))
print(summarize_scores("Rohan", 74, 80))10.8 Positional-Only, Keyword-Only, and Unpacking at Call Sites
Modern Python function signatures offer fine-grained control over how callers pass arguments. Placing a forward slash / in a parameter list designates all preceding parameters as positional-only, whereas placing an asterisk * designates all following parameters as keyword-only. For example, in def compute(x, y, /, *, precision=2):, x and y must be passed positionally while precision must be passed by keyword. At the call site, the unary unpacking operators * and ** expand sequences into positional arguments and dictionaries into keyword arguments respectively (func(*coords, **options)).
10.9 Closures and Higher-Order Function Pipelines
Because Python treats functions as first-class objects, functions can be stored in data structures, passed as arguments to other functions, and returned from outer functions. When an inner function references variables from its enclosing function's scope and the outer function returns that inner function, Python creates a closure—preserving the enclosing variable bindings even after the outer function has finished executing. Closures form the foundation for factory functions and decorators.
from functools import reduce
def make_multiplier(factor):
def multiply(value):
return value * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print("Double 15:", double(15), "| Triple 15:", triple(15))
# Functional pipeline: filter passing marks, apply 5-mark grace, sum total
raw_marks = [32, 48, 71, 25, 84, 59]
passing = filter(lambda m: m >= 40, raw_marks)
adjusted = map(lambda m: min(m + 5, 100), passing)
total_adjusted = reduce(lambda acc, m: acc + m, adjusted, 0)
print("Total adjusted passing marks:", total_adjusted)10.10 Classical Recursive Algorithms: Tower of Hanoi and Merge Sort
Recursion shines when a problem decomposes naturally into smaller self-similar subproblems. Two canonical examples in computer science are the Tower of Hanoi puzzle and Merge Sort. In the Tower of Hanoi with disks, moving all disks from source peg A to destination peg C using auxiliary peg B requires moving disks from A to B, moving the largest disk directly from A to C, and finally moving the disks from B to C. The minimum number of moves satisfies the recurrence .
def hanoi(n, src, aux, dst):
if n == 1:
print(f"Move disk 1: {src} -> {dst}")
return
hanoi(n - 1, src, dst, aux)
print(f"Move disk {n}: {src} -> {dst}")
hanoi(n - 1, aux, src, dst)
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
hanoi(3, "A", "B", "C")
print("Sorted:", merge_sort([38, 27, 43, 3, 9, 82, 10]))10.11 Nested Loop Patterns, Sentinel Loops, and Matrix Processing
Nested loops are indispensable for processing two-dimensional nested lists—such as computing row sums, column sums, matrix multiplication, or searching grids. When searching a 2D matrix for a target value, a single break exits only the inner loop; combining a flag or encapsulating the search inside a helper function with an early return exits all nested loops cleanly without convoluted state variables. Similarly, sentinel-controlled while loops paired with continue skip invalid records without terminating the input stream.
A = [[1, 2, 3], [4, 5, 6]] # 2x3 matrix
B = [[7, 8], [9, 10], [11, 12]] # 3x2 matrix
rows_a, cols_a = len(A), len(A[0])
cols_b = len(B[0])
# Nested loop matrix multiplication
product = [[0 for _ in range(cols_b)] for _ in range(rows_a)]
for i in range(rows_a):
for j in range(cols_b):
for k in range(cols_a):
product[i][j] += A[i][k] * B[k][j]
print("Matrix Product:", product)
# Equivalent comprehension form
product_comp = [
[sum(A[i][k] * B[k][j] for k in range(cols_a)) for j in range(cols_b)]
for i in range(rows_a)
]
print("Comprehension Product:", product_comp)10.12 Iterative vs. Recursive Design Trade-Offs
Every recursive algorithm can be rewritten iteratively using an explicit loop and, when necessary, an explicit stack data structure. Choosing between recursion and iteration requires balancing algorithmic clarity against memory overhead and call-depth limits. Recursive solutions excel on naturally hierarchical or divide-and-conquer structures—such as binary trees, file-system hierarchies, nested JSON documents, and Merge Sort—where the recursion depth is logarithmic () or bounded by tree height. Conversely, linear tail-recursive problems such as summing an array or computing are far more memory-efficient when written iteratively, because Python does not perform Tail-Call Optimization (TCO); each recursive call consumes a full stack frame and risks RecursionError once depth exceeds 1,000.
| Criterion | Recursive Implementation | Iterative Implementation |
|---|---|---|
| Space Complexity | stack frames for recursion depth . | Typically auxiliary variables (unless explicit stack needed). |
| Execution Speed | Higher overhead per step due to Python function-call frame allocation. | Faster loop execution with minimal call-stack overhead. |
| Depth Limit | Bounded by sys.getrecursionlimit() (default 1000). |
Bounded only by available system memory. |
| Best Problem Fit | Tree/graph traversals, backtracking, divide-and-conquer sorting. | Sequential scans, accumulators, tabular aggregations, streaming I/O. |
10.13 Multi-Criteria Sorting with Lambda Keys and Functional Composition
Python's sorted() and list.sort() accept a key callable that transforms each element into a comparison key once per element (the Schwartzian transform). Returning a tuple from a lambda key enables multi-level sorting cleanly—for example, sorting student tuples (name, semester, cgpa) by descending CGPA and then ascending name alphabetically. Because Python's Timsort algorithm is guaranteed to be stable, elements with equal keys preserve their original relative order, allowing complex multi-pass sorts as well.
students = [
("Ananya", 4, 9.1),
("Bipin", 4, 8.5),
("Chitra", 4, 9.1),
("Deepak", 4, 7.9)
]
# Sort by CGPA descending (-x[2]), then name ascending (x[0])
ranked = sorted(students, key=lambda s: (-s[2], s[0]))
for name, sem, cgpa in ranked:
print(f"{name:<8} | Sem {sem} | CGPA: {cgpa:.1f}")
# Fast exponentiation (exponentiation by squaring) in O(log n)
def fast_power(base, exp):
if exp == 0:
return 1
half = fast_power(base, exp // 2)
if exp % 2 == 0:
return half * half
return base * half * half
print("2^10 =", fast_power(2, 10))10.14 Comprehensions Scope Isolation and Guarded Control Flows
In Python 3, list comprehensions execute inside their own isolated local scope. Unlike a standard for loop—where the loop variable remains bound in the enclosing scope after the loop finishes—a comprehension's iteration variable never leaks into or overwrites an outer variable of the same name. Furthermore, combining elif dispatch tables or dictionary-mapped functions with clean helper routines eliminates deeply nested if-elif-else chains, producing modular, testable code.
def flatten_nested(items):
result = []
for elem in items:
if isinstance(elem, list):
result.extend(flatten_nested(elem))
else:
result.append(elem)
return result
nested = [1, [2, [3, 4], 5], [6, 7], 8]
print("Flattened:", flatten_nested(nested))
# Dispatch table replacing long if-elif chains
operations = {
"add": lambda a, b: a + b,
"sub": lambda a, b: a - b,
"mul": lambda a, b: a * b,
"div": lambda a, b: a / b if b != 0 else None,
}
print("Dispatch mul(6, 7):", operations["mul"](6, 7))10.15 Generator Expressions vs. List Comprehensions for Lazy Iteration
While a list comprehension ([x * x for x in range(1_000_000)]) allocates all one million integers in RAM simultaneously, replacing square brackets with parentheses creates a generator expression ((x * x for x in range(1_000_000))). A generator expression produces values lazily one item at a time in memory, making it ideal for feeding reductions such as sum(), max(), any(), and all() over large datasets or file streams.
import sys
eager_squares = [x * x for x in range(10000)]
lazy_squares = (x * x for x in range(10000))
print("Eager list bytes:", sys.getsizeof(eager_squares))
print("Lazy gen bytes: ", sys.getsizeof(lazy_squares))
print("Sum via lazy gen:", sum(lazy_squares))10.16 Docstrings, Type Hints, and Modular Function Design
Well-engineered Python functions adhere to the Single Responsibility Principle: each function performs one cohesive task, accepts explicit parameters rather than relying on hidden global state, and documents its contract with a PEP 257 docstring ("""Compute ...""") and optional PEP 484 type annotations (def area(radius: float) -> float:). Type annotations do not enforce runtime type errors by themselves in CPython, but they enable static analyzers, IDE autocompletion, and clearer API documentation.
When designing recursive or iterative helper routines, guarding preconditions at the top of the function with early returns—known as guard clauses—reduces indentation depth and makes invalid-input handling immediately visible to any reader.
def compute_grade_average(scores: list[float]) -> float:
"""Return the arithmetic mean of a non-empty list of valid scores."""
if not scores:
raise ValueError("Score list cannot be empty.")
if any(s < 0 or s > 100 for s in scores):
raise ValueError("All scores must lie within 0 to 100.")
return sum(scores) / len(scores)
print("Mean score:", compute_grade_average([82.5, 90.0, 87.5]))Module IV: Packages, Files, Exception Handling & OOP
Chapter 11: Modules, Packages, Namespaces, and Scope
11.1 Built-in Modules, User Modules, and Import Mechanics
A Python module is any file ending in .py that groups related functions, classes, and constants into a reusable unit. Python ships with extensive built-in and standard-library modules such as math, random, os, sys, and datetime. Developers create custom modules simply by saving Python definitions in a file (for instance, geometry.py) and importing them elsewhere.
The import statement supports several forms: import math (binds the module namespace), import math as m (binds an alias), from math import sqrt, pi (binds specific attributes directly into the caller's namespace), and from math import * (wildcard import, discouraged in production code because it pollutes namespaces and obscures symbol origins). When importing a module, Python searches directories in sys.path in a fixed order: the directory containing the running script, directories listed in the PYTHONPATH environment variable, and standard library / site-packages directories. During module development in an interactive session, importlib.reload(mod) forces Python to re-execute an already-loaded module file.
11.2 Namespaces, LEGB Scope, and Introspection
A namespace is a mapping from symbolic names to object references, implemented internally as a dictionary. Python resolves unqualified variable names using the LEGB rule in strict priority order: Local (names assigned inside the current function), Enclosing (names in outer enclosing functions for closures), Global (module-level names), and Built-in (predefined names such as len and print). Inside a function, assigning to a name creates a local variable by default; modifying a module-level variable requires an explicit global var_name declaration, while modifying an enclosing function variable requires nonlocal var_name. The built-in dir(obj) function returns a sorted list of valid attribute names defined on a module or object, aiding interactive inspection.
11.3 Packages in Python
A package is a directory hierarchy of modules that prevents naming collisions in large software projects. Traditionally, a directory becomes a regular Python package when it contains an __init__.py file (which may be empty or execute package-level initialization). Sub-modules are accessed using dotted notation such as import finance.tax.gst or from finance.tax import gst. The special variable __name__ evaluates to "__main__" when a file is executed directly as a script, but evaluates to the module's dotted name when imported—enabling the idiom if __name__ == "__main__": to guard test or CLI entry points.
Chapter 12: File Handling and Directory Management
12.1 Opening, Reading, Writing, and Closing Files
Persistent data storage beyond program termination requires file handling. Python's built-in open(filename, mode, encoding='utf-8') function returns a file object connected to an operating system stream. Always closing files via f.close() flushes buffered writes and releases OS file descriptors. The preferred Pythonic pattern uses the with context manager (with open(...) as f:), which guarantees automatic closure even if an exception occurs mid-operation.
| File Mode | Operation | Pointer Start | Behavior if File Exists / Missing |
|---|---|---|---|
'r' |
Read text (default) | Beginning | Raises FileNotFoundError if missing. |
'w' |
Write text | Beginning | Truncates existing file to zero length; creates if missing. |
'a' |
Append text | End of file | Preserves existing content; creates if missing. |
'x' |
Exclusive creation | Beginning | Raises FileExistsError if file already exists. |
'r+' / 'w+' |
Read & write | Beginning | 'r+' preserves content; 'w+' truncates first. |
'rb' / 'wb' |
Binary read / write | Beginning | Reads/writes raw bytes without newline translation. |
Key file methods include read(size) (reads entire file or up to size characters), readline() (reads a single line including trailing \n), readlines() (returns a list of all lines), write(s) (writes string and returns character count), writelines(seq), tell() (returns current byte offset), and seek(offset, whence) (repositions the file cursor).
12.2 Renaming, Deleting, and Directory Operations
File-system metadata and directory management are handled through the standard os module (and object-oriented pathlib). Common operations include os.rename(src, dst) to rename or move a file, os.remove(path) (or os.unlink()) to delete a file, os.getcwd() to inspect the current working directory, os.mkdir(path) / os.makedirs(path, exist_ok=True) to create directories, os.listdir(path) to list directory entries, os.rmdir(path) to remove an empty directory, and os.path.exists(path) to check path existence safely.
import os
filename = "lab_log.txt"
with open(filename, "w", encoding="utf-8") as fh:
fh.write("Session 1: Python File I/O\n")
fh.writelines(["Line A\n", "Line B\n"])
with open(filename, "r", encoding="utf-8") as fh:
print("Cursor start:", fh.tell())
first_line = fh.readline().strip()
remaining = fh.read()
print("First:", first_line, "| Rest bytes:", len(remaining))
if os.path.exists(filename):
os.rename(filename, "lab_log_archived.txt")
os.remove("lab_log_archived.txt")Chapter 13: Exception Handling
13.1 Built-in Exceptions and Try-Except Control Flow
An exception is a runtime event that disrupts normal sequential execution when an error condition occurs—such as dividing by zero (ZeroDivisionError), accessing an out-of-range index (IndexError), looking up a missing dictionary key (KeyError), passing an incompatible type (TypeError), converting an invalid string (ValueError), or opening a missing file (FileNotFoundError). All standard exceptions inherit from BaseException, with recoverable runtime errors inheriting from Exception.
Python handles exceptions cleanly using the four-clause try ... except ... else ... finally construct. Code that might fail is placed inside try. Matching except ExcType as err: blocks catch specific exceptions and bind the exception object (carrying diagnostic arguments in err.args). The optional else block executes only if no exception was raised in try, while the finally block always executes regardless of whether an exception occurred, making it ideal for cleanup actions.
13.2 Raising Exceptions and User-Defined Exceptions
Programmers can explicitly trigger exceptions using raise ValueError("Age cannot be negative") to enforce domain invariants. For application-specific error hierarchies, developers define custom exception classes by subclassing Exception, optionally storing structured error codes or contextual metadata in custom attributes.
class InsufficientBalanceError(Exception):
def __init__(self, balance, amount):
super().__init__(f"Cannot withdraw {amount}; available balance is {balance}")
self.balance = balance
self.amount = amount
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Withdrawal amount must be positive.")
if amount > balance:
raise InsufficientBalanceError(balance, amount)
return balance - amount
try:
new_bal = withdraw(5000, 6500)
except InsufficientBalanceError as err:
print("Domain Error:", err, "| Shortfall:", err.amount - err.balance)
except ValueError as err:
print("Input Error:", err)
else:
print("Updated balance:", new_bal)
finally:
print("Transaction audit logged.")Chapter 14: Object-Oriented Programming in Python
14.1 Classes, Objects, Methods, and Attributes
Object-Oriented Programming (OOP) models software systems as interacting objects that bundle state (attributes) and behavior (methods). A class serves as the blueprint defining shared structure, while an object is a concrete runtime instance created by calling the class (acc = BankAccount("Asha", 1000)). Instance methods always receive the calling instance as their implicit first parameter, conventionally named self.
Python distinguishes sharply between instance attributes and static (class) attributes. Instance attributes are bound to self (for example, self.balance = 1000) and hold independent values for each object. Class attributes are defined directly inside the class body outside any method (for example, interest_rate = 0.04) and are shared across all instances of that class. Python also supports @classmethod (receives cls) and @staticmethod (utility function bound to the class namespace without self or cls).
14.2 Constructors, Destructors, Encapsulation, and Data Hiding
The initializer method __init__(self, ...) acts as Python's constructor logic: immediately after __new__ allocates the object, Python invokes __init__ to initialize instance attributes. Conversely, the destructor __del__(self) is invoked when an object's reference count drops to zero and the garbage collector reclaims it, though deterministic resource cleanup should always rely on with context managers rather than __del__.
Encapsulation binds data and the methods operating on that data inside a single class boundary, exposing a controlled public interface while restricting direct external tampering. Python implements data hiding via naming conventions and name mangling: a single leading underscore (_balance) signals an internal/protected attribute by convention, whereas a double leading underscore (__pin) triggers name mangling to _ClassName__pin, preventing accidental external access or subclass collisions. Public getter/setter methods or @property decorators validate state transitions cleanly.
class StudentAccount:
institution = "University of Kerala" # Static / class attribute
def __init__(self, name, credits_earned=0):
self.name = name # Public instance attribute
self._status = "Active" # Protected convention
self.__credits = credits_earned # Name-mangled private attribute
def add_credits(self, count):
if count <= 0:
raise ValueError("Credits must be positive.")
self.__credits += count
def get_credits(self):
return self.__credits
def __del__(self):
# Called when object is garbage-collected
pass
s1 = StudentAccount("Meera", 16)
s1.add_credits(4)
print(s1.name, "| Institution:", StudentAccount.institution, "| Credits:", s1.get_credits())14.3 Properties, Inheritance, Polymorphism, and Dunder Methods
Beyond basic encapsulation, Python supports clean attribute validation via the @property decorator, allowing methods to be accessed with attribute syntax while enforcing invariants behind the scenes. Furthermore, inheritance enables a derived subclass to inherit attributes and methods from a base superclass (class GraduateAccount(StudentAccount):), extend behavior, and override parent methods while delegating shared initialization via super().__init__(...). Polymorphism allows distinct classes sharing a common method interface (such as calculate_gpa() or area()) to be processed uniformly through duck typing.
Python classes also customize built-in operators and functions by implementing special "dunder" (double-underscore) methods: __str__ provides a human-friendly string representation for print(), __repr__ provides an unambiguous developer representation, __eq__ defines value equality for ==, and __len__ enables len(obj).
class CourseRecord:
def __init__(self, code, title, credits):
self.code = code
self.title = title
self._credits = credits
@property
def credits(self):
return self._credits
@credits.setter
def credits(self, value):
if not (1 <= value <= 6):
raise ValueError("Course credits must be between 1 and 6.")
self._credits = value
def __str__(self):
return f"{self.code}: {self.title} ({self._credits} Cr)"
class LabCourseRecord(CourseRecord):
def __init__(self, code, title, credits, lab_hours):
super().__init__(code, title, credits)
self.lab_hours = lab_hours
def __str__(self):
return f"{super().__str__()} [Lab: {self.lab_hours} hrs/wk]"
c = LabCourseRecord("UK4DSCCAP203", "Python Programming", 4, 2)
c.credits = 4
print(c)14.4 Standard Exception Hierarchy and Directory Traversal
When designing robust file-processing and OOP applications, catching overly broad exceptions (such as a bare except:) masks programming bugs like NameError or interrupts like KeyboardInterrupt. Instead, developers inspect Python's standard exception hierarchy to catch only expected failure modes at the right level of abstraction.
| Exception Class | Parent Class | Common Trigger Condition |
|---|---|---|
ZeroDivisionError |
ArithmeticError |
Dividing or taking modulo by zero (10 / 0, 10 % 0). |
IndexError |
LookupError |
Accessing a sequence index outside valid bounds. |
KeyError |
LookupError |
Looking up a nonexistent key in a dictionary via d[k]. |
ValueError |
Exception |
Correct argument type but invalid value (e.g., int("abc")). |
TypeError |
Exception |
Operation applied to an inappropriate type (e.g., "a" + 5). |
FileNotFoundError |
OSError |
Attempting to open or remove a file path that does not exist. |
14.5 Package Architecture, Relative Imports, and sys.path Resolution
In multi-module Python applications, organizing files into packages prevents global name collisions and clarifies architectural boundaries. Consider a project layout containing a top-level package erp/ with __init__.py, a subpackage erp/billing/ containing __init__.py and invoice.py, and a sibling module erp/utils.py. Inside invoice.py, developers can use either an absolute import (from erp.utils import format_currency) or a relative import (from ..utils import format_currency, where .. ascends one package level).
When Python encounters an import statement, it first checks the sys.modules cache dictionary; if the module is already loaded, Python reuses the cached module object immediately. Otherwise, Python scans directories listed in sys.path sequentially, locates the matching .py file or package directory, compiles it to bytecode if needed, and executes its top-level statements once. During interactive debugging, calling importlib.reload(mod) re-executes the module file in place, though existing object references bound before the reload retain their old definitions.
14.6 Random-Access File Pointer Control and Directory Traversal
Sequential reading processes a file from byte 0 to End-of-File (EOF), whereas random-access operations reposition the internal file cursor using seek(offset, whence). In binary mode ('rb' / 'wb'), whence=0 seeks relative to the file start, whence=1 seeks relative to the current cursor position, and whence=2 seeks relative to the end of the file (for instance, fh.seek(-16, 2) jumps 16 bytes before EOF). In text mode, seek() only permits offsets returned by tell() or seek(0) due to variable-width UTF-8 character encoding.
For recursive directory inspection, os.walk(root_path) yields a three-tuple (dirpath, dirnames, filenames) for every directory in a tree, enabling automated log scanners, backup utilities, and file-extension audits in a few lines of code.
import os
def safe_read_tail(path, num_bytes=32):
try:
with open(path, "rb") as fh:
fh.seek(0, os.SEEK_END)
size = fh.tell()
start = max(0, size - num_bytes)
fh.seek(start, os.SEEK_SET)
return fh.read()
except OSError as err:
raise RuntimeError(f"Failed to read tail of {path}") from err
# Inspect current directory entries safely
entries = os.listdir(".")
py_files = [name for name in entries if name.endswith(".py")]
print("Python scripts in CWD:", len(py_files))14.7 Operator Overloading, Multiple Inheritance, and Method Resolution Order
Python enables custom classes to integrate seamlessly with built-in operators through operator overloading—implementing special dunder methods such as __add__ (+), __sub__ (-), __eq__ (==), and __lt__ (<). When two objects are added via v1 + v2, Python invokes v1.__add__(v2). If v2 is an incompatible type, returning NotImplemented allows Python to fall back cleanly to v2.__radd__(v1) or raise TypeError.
Python also supports multiple inheritance, where a class derives from more than one base class (class HybridDevice(Scanner, Printer):). To resolve attribute and method lookups unambiguously across diamond-shaped inheritance graphs, Python computes a deterministic Method Resolution Order (MRO) using the C3 linearization algorithm, inspectable via ClassName.__mro__ or ClassName.mro(). Cooperative super() calls follow this linearized MRO chain, guaranteeing each ancestor initializer executes exactly once.
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if not isinstance(other, Vector2D):
return NotImplemented
return Vector2D(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return isinstance(other, Vector2D) and self.x == other.x and self.y == other.y
def __repr__(self):
return f"Vector2D({self.x}, {self.y})"
v1 = Vector2D(3, 4)
v2 = Vector2D(1, 2)
print("Sum:", v1 + v2, "| Equal?", v1 == Vector2D(3, 4))14.8 Composition vs. Inheritance and Abstract Base Classes
While inheritance models an "is-a" relationship (for example, a LabCourseRecord is a CourseRecord), composition models a "has-a" relationship by storing instances of helper classes as attributes inside another class (for example, a Department object contains a list of CourseRecord objects). Software engineering best practices favor composition over deep inheritance hierarchies because composition minimizes tight coupling and allows components to be swapped dynamically at runtime.
When a base class defines a common contract that all subclasses must implement, Python's standard abc module provides ABC (Abstract Base Class) and the @abstractmethod decorator. Attempting to instantiate an abstract class directly—or instantiating a subclass that fails to override every abstract method—raises TypeError immediately at instantiation time, enforcing interface compliance early.
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
pass
class UPIPayment(PaymentMethod):
def __init__(self, vpa):
self.vpa = vpa
def pay(self, amount):
return f"Paid Rs. {amount:.2f} via UPI ({self.vpa})"
class OrderProcessor:
def __init__(self, method: PaymentMethod):
self.method = method # Composition
def checkout(self, total):
return self.method.pay(total)
processor = OrderProcessor(UPIPayment("student@okaxis"))
print(processor.checkout(1250.0))14.9 Custom Context Managers and Deterministic Resource Cleanup
Relying on the destructor __del__() to close files or network sockets is unsafe because garbage collection timing is non-deterministic—particularly when reference cycles exist. Instead, Python's with statement invokes the context management protocol via two dunder methods: __enter__(self) acquires and returns the resource, while __exit__(self, exc_type, exc_val, exc_tb) guarantees deterministic cleanup even when an exception propagates out of the block.
14.10 Deep Dive: LEGB Scope, global, nonlocal, and Introspection
Inside nested functions, Python's LEGB lookup reads outer variables seamlessly, but any assignment statement binds a new local variable unless explicitly declared otherwise. Using global counter inside a function directs assignments to the module-level namespace, whereas nonlocal counter inside an inner closure directs assignments to the nearest enclosing function's namespace (never module-global). Combined with introspection utilities—dir(obj) to list attributes, hasattr(obj, name), getattr(obj, name), and isinstance(obj, cls)—developers can inspect and debug complex object graphs dynamically.
def make_counter(start=0):
count = start
def increment(step=1):
nonlocal count
count += step
return count
return increment
c = make_counter(10)
print("Counter:", c(), c(5))
class ManagedSession:
def __init__(self, label):
self.label = label
def __enter__(self):
print(f"[OPEN] {self.label}")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"[CLOSE] {self.label} | Error: {exc_type is not None}")
return False # Do not suppress exceptions
with ManagedSession("GradeImport"):
print("Processing grade records...")14.11 Structured Text Persistence: CSV and JSON File Handling
While plain-text read() and write() suffice for unstructured logs, tabular and hierarchical application data is routinely persisted using Python's standard csv and json modules. The csv.DictReader and csv.DictWriter classes map spreadsheet rows directly to Python dictionaries, handling embedded commas and quotes automatically (always open CSV files with newline=""). For nested dictionaries and lists, json.dump(obj, fh, indent=2) serializes Python structures to portable JSON text, and json.load(fh) reconstructs them cleanly.
import json
import os
config_data = {
"course": "UK4DSCCAP203",
"semester": 4,
"topics": ["Modules", "Files", "Exceptions", "OOP"]
}
json_path = "course_meta.json"
with open(json_path, "w", encoding="utf-8") as fh:
json.dump(config_data, fh, indent=2)
with open(json_path, "r", encoding="utf-8") as fh:
loaded = json.load(fh)
print("Loaded JSON course:", loaded["course"], "| Topics:", len(loaded["topics"]))
if os.path.exists(json_path):
os.remove(json_path)14.12 Class Methods, Static Methods, and Factory Constructors
In addition to standard instance methods bound to self, Python classes support two specialized method decorators: @classmethod and @staticmethod. A class method receives the class object itself as its first argument (cls) and is commonly used to implement alternative factory constructors—such as parsing a string record into an object instance (Student.from_csv("101,Ananya")). A static method receives neither self nor cls and serves as a pure utility helper logically grouped inside the class namespace (for example, validating a roll number format before object creation).
class CourseEnrollment:
passing_score = 40
def __init__(self, roll_no, score):
self.roll_no = roll_no
self.score = score
@classmethod
def from_string(cls, record_str):
roll_str, score_str = record_str.split(",")
return cls(int(roll_str.strip()), float(score_str.strip()))
@staticmethod
def is_valid_score(score):
return 0.0 <= score <= 100.0
def has_passed(self):
return self.score >= CourseEnrollment.passing_score
e = CourseEnrollment.from_string("105, 86.5")
print("Valid?", CourseEnrollment.is_valid_score(e.score), "| Passed?", e.has_passed())14.13 Encapsulation with __slots__ and Defensive Copying
By default, every Python instance stores its attributes in a per-object dictionary named __dict__, which enables dynamic attribute addition at runtime at the cost of extra memory per instance. Defining a class-level __slots__ = ("roll_no", "name") tuple replaces __dict__ with fixed-offset C-level descriptors, shrinking memory overhead for millions of objects and preventing accidental typos when assigning attributes.
Furthermore, when an object exposes internal mutable collections (such as a list of enrolled courses) through a getter method or @property, returning a direct reference allows external callers to mutate private state undetected. Returning a defensive copy (return list(self.__courses)) preserves strict encapsulation and data hiding invariants.
Module V: Regular Expressions & Database Programming
Chapter 15: Pattern Matching with Regular Expressions
15.1 Fundamentals of Regular Expressions and the re Module
A regular expression (regex) is a formal pattern string that describes a set of matching character sequences using literal characters combined with special metacharacters. Regular expressions power input validation (emails, phone numbers, course codes), log parsing, lexical analysis, and structured text extraction. Python's standard re module provides a high-performance regex engine.
Always write regex patterns using Python raw string literals (r"\d+\.\d+") so that backslashes reach the regex engine intact rather than being interpreted as Python string escape sequences. When a pattern is reused repeatedly inside loops, precompiling it via pattern = re.compile(r"...") avoids redundant pattern parsing overhead.
15.2 Core re Functions: match, search, findall, finditer, sub, split
| Function | Matching Scope | Return Type | Typical Use Case |
|---|---|---|---|
re.match(pat, s) |
Anchored strictly at index 0 (beginning of string). | Match object or None |
Validating prefix formats or tokenizing from start. |
re.search(pat, s) |
Scans the entire string and returns the first match. | Match object or None |
Checking whether a pattern appears anywhere in text. |
re.findall(pat, s) |
Finds all non-overlapping matches in the string. | list of strings or tuples |
Extracting all emails, numbers, or hashtags. |
re.finditer(pat, s) |
Lazily yields all non-overlapping matches in order. | Iterator of Match objects |
Accessing both matched text and .span() offsets. |
re.sub(pat, repl, s) |
Replaces occurrences of pat with repl. |
Modified str |
Sanitizing whitespace, masking sensitive digits. |
re.split(pat, s) |
Splits string wherever pat matches. |
list of strings |
Tokenizing text with irregular delimiters. |
15.3 Metacharacters, Character Classes, Quantifiers, and Grouping
Regex expressiveness stems from combining character classes, anchors, quantifiers, and capturing groups:
- Metacharacters & Anchors:
.matches any character except newline;^anchors to the start of a string (or line withre.M);$anchors to the end;|denotes alternation (OR);\bmatches a word boundary. - Character Classes: Bracket expressions such as
[A-Za-z0-9_]match any single character inside the set, while[^0-9]matches any character except digits. Predefined shorthands include\d(digit),\D(non-digit),\w(word character),\W(non-word),\s(whitespace), and\S(non-whitespace). - Quantifiers: Specify repetition counts for the preceding token:
*(0 or more),+(1 or more),?(0 or 1),{n}(exact count), and{m,n}(between and inclusive). Quantifiers are greedy by default; appending?(such as.*?) switches to non-greedy (lazy) matching. - Grouping and Flags: Parentheses
(...)capture sub-matches accessible viamatch.group(1), while(?:...)groups without capturing. Compilation flags includere.IGNORECASE(re.I),re.MULTILINE(re.M), andre.DOTALL(re.S).
import re
course_pattern = re.compile(r"^UK([1-8])([A-Z]{3})([A-Z]{3})(\d{3})quot;)
m = course_pattern.match("UK4DSCCAP203")
if m:
print("Valid Course -> Sem:", m.group(1), "| Category:", m.group(2), "| Num:", m.group(4))
log_text = "Users: 104, Errors: 2, Latency: 45ms"
numbers = re.findall(r"\d+", log_text)
masked = re.sub(r"\d+", "#", log_text)
print("Extracted numbers:", numbers)
print("Masked log:", masked)Chapter 16: Database Programming with Python
16.1 Python DB-API 2.0 Architecture
Relational databases store structured records in normalized tables queried through Structured Query Language (SQL). To provide a uniform programming interface across diverse database engines (SQLite, MySQL, PostgreSQL), Python standardizes database drivers around PEP 249 (DB-API 2.0). Regardless of the backend driver, every DB-API workflow follows an identical lifecycle: establish a Connection object via connect(), obtain a Cursor object via conn.cursor(), execute SQL statements via cursor.execute(), commit or roll back transactions on the connection, fetch query rows, and close both cursor and connection.
Python includes the serverless, file-based sqlite3 module directly in its standard library, making it ideal for embedded applications, desktop tools, and rapid prototyping. External enterprise servers such as MySQL use third-party DB-API drivers (for example, mysql.connector) with identical cursor semantics.
16.2 Connecting to a Database and Creating Tables
Calling sqlite3.connect("college.db") opens an existing SQLite database file or creates it if absent (passing ":memory:" creates a fast transient RAM database). For MySQL, mysql.connector.connect(host=..., user=..., password=..., database=...) establishes a TCP session. Tables are defined using SQL Data Definition Language (DDL) statements such as CREATE TABLE IF NOT EXISTS with primary keys, data types, and integrity constraints.
16.3 Parameterized Queries and SQL Injection Prevention
Never construct SQL statements by concatenating or formatting untrusted user input directly into SQL strings, as doing so exposes the database to SQL injection attacks. Instead, always pass user values through parameterized placeholders—? in sqlite3 or %s in mysql.connector—allowing the database driver to bind and escape parameters safely at the protocol level.
16.4 CRUD Operations: INSERT, READ (SELECT), UPDATE, and DELETE
Data Manipulation Language (DML) operations manage table records within ACID transactions. Modifications (INSERT, UPDATE, DELETE) remain isolated until conn.commit() persists them permanently, or conn.rollback() discards them on error.
| CRUD Operation | SQL Statement | Python Cursor Method | Post-Execution Step |
|---|---|---|---|
| Create (Insert) | INSERT INTO students VALUES (?, ?, ?) |
cur.execute(sql, params) / executemany() |
Call conn.commit() to persist rows. |
| Read (Select) | SELECT id, name, gpa FROM students WHERE gpa >= ? |
cur.execute(sql, params) |
Retrieve via fetchone(), fetchmany(n), or fetchall(). |
| Update | UPDATE students SET gpa = ? WHERE id = ? |
cur.execute(sql, params) |
Inspect cur.rowcount; call conn.commit(). |
| Delete | DELETE FROM students WHERE id = ? |
cur.execute(sql, params) |
Inspect cur.rowcount; call conn.commit(). |
import sqlite3
with sqlite3.connect(":memory:") as conn:
cur = conn.cursor()
# 1. CREATE TABLE
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
roll_no INTEGER PRIMARY KEY,
name TEXT NOT NULL,
semester INTEGER NOT NULL,
cgpa REAL CHECK (cgpa >= 0.0 AND cgpa <= 10.0)
)
""")
# 2. INSERT (Single and Batch)
cur.execute("INSERT INTO students VALUES (?, ?, ?, ?)", (101, "Ananya", 4, 8.9))
cur.executemany(
"INSERT INTO students VALUES (?, ?, ?, ?)",
[(102, "Bipin", 4, 7.8), (103, "Chitra", 4, 9.2)]
)
conn.commit()
# 3. READ (SELECT)
cur.execute("SELECT roll_no, name, cgpa FROM students WHERE cgpa >= ?", (8.0,))
for row in cur.fetchall():
print("High Achiever:", row)
# 4. UPDATE
cur.execute("UPDATE students SET cgpa = ? WHERE roll_no = ?", (8.4, 102))
conn.commit()
print("Rows updated:", cur.rowcount)
# 5. DELETE
cur.execute("DELETE FROM students WHERE roll_no = ?", (101,))
conn.commit()
print("Rows deleted:", cur.rowcount)16.5 Named Regex Groups, Lookarounds, and Real-World Validation
Complex text extraction benefits from named capturing groups (?P<name>pattern), which allow matched fields to be retrieved by semantic key via match.group("name") or as a dictionary via match.groupdict(). Additionally, zero-width lookahead assertions—positive (?=...) and negative (?!...)—verify that a pattern is followed (or not followed) by another sub-pattern without consuming characters from the match span. Lookaheads are widely used in password strength validators that require at least one uppercase letter, one digit, and a minimum length simultaneously.
| Validation Target | Regular Expression Pattern | Pattern Explanation |
|---|---|---|
| Email Address | r"^[\w.+-]+@[\w-]+\.[A-Za-z]{2,}$" |
Local part, @ symbol, domain label, and TLD of at least 2 letters. |
| Indian Mobile Number | r"^(?:\+91[-\s]?)?[6-9]\d{9}$" |
Optional +91 prefix followed by 10 digits starting with 6–9. |
| ISO Date (YYYY-MM-DD) | r"^(?P<year>\d{4})-(?P<month>0[1-9]|1[0-2])-(?P<day>0[1-9]|[12]\d|3[01])$" |
Named groups validating 4-digit year, months 01–12, and days 01–31. |
| Strong Password | r"^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$" |
Lookaheads enforce uppercase, digit, special symbol, and length ≥ 8. |
16.6 SQLite vs. MySQL Drivers, Transactions, and Row Factories
While sqlite3 embeds the database engine directly inside the Python process using a single disk file, client-server RDBMS engines such as MySQL run as separate network daemons accessed over TCP/IP using mysql.connector. Both adhere to PEP 249 DB-API 2.0, differing primarily in connection arguments and parameter placeholder syntax.
| Aspect | sqlite3 (Standard Library) |
mysql.connector (MySQL Driver) |
|---|---|---|
| Architecture | Serverless, embedded single-file database. | Client-server daemon over TCP/IP sockets. |
| Connection Call | sqlite3.connect("app.db") |
mysql.connector.connect(host=..., user=..., password=..., database=...) |
| Parameter Placeholder | Question mark ? (qmark style). |
Percent-s %s (pyformat / format style). |
| Named Row Access | conn.row_factory = sqlite3.Row |
conn.cursor(dictionary=True) |
To preserve ACID atomicity during multi-step updates (such as transferring credits or recording an invoice), wrap database modifications in a try ... except sqlite3.Error block: call conn.commit() only after all statements succeed, and call conn.rollback() in the except block if any constraint violation occurs.
import re
import sqlite3
EMAIL_RE = re.compile(r"^[\w.+-]+@[\w-]+\.[A-Za-z]{2,}quot;)
def register_student(conn, roll_no, name, email):
if not EMAIL_RE.match(email):
raise ValueError(f"Invalid email format: {email}")
try:
cur = conn.cursor()
cur.execute(
"INSERT INTO directory (roll_no, name, email) VALUES (?, ?, ?)",
(roll_no, name, email)
)
conn.commit()
except sqlite3.Error as err:
conn.rollback()
print("Database transaction rolled back:", err)
with sqlite3.connect(":memory:") as conn:
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE directory (roll_no INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
register_student(conn, 201, "Kiran", "[email protected]")
row = conn.execute("SELECT * FROM directory WHERE roll_no = ?", (201,)).fetchone()
if row:
print("Stored:", row["roll_no"], row["name"], row["email"])16.7 Greedy vs. Lazy Quantifiers, Backreferences, and Callback Substitution
By default, regex quantifiers (*, +, ?, {m,n}) are greedy: they consume as many characters as possible while still allowing the overall pattern to succeed. When parsing delimited tags such as "<b>first</b> and <b>second</b>", the greedy pattern r"<b>.*</b>" matches the entire string from the first opening tag to the final closing tag. Appending ? creates a lazy (non-greedy) quantifier (r"<b>.*?</b>"), which consumes the minimum characters required, matching "<b>first</b>" and "<b>second</b>" separately.
Backreferences (\1, \2) match the exact text previously captured by an earlier parenthesized group—ideal for detecting repeated consecutive words (r"\b(\w+)\s+\1\b") or matching symmetric delimiters. Furthermore, re.sub(pattern, func, text) accepts a Python callable instead of a static replacement string; the engine invokes func(match) for every match and substitutes its returned string dynamically.
import re
html = "<em>Python</em> and <em>SQLite</em>"
greedy = re.findall(r"<em>.*</em>", html)
lazy = re.findall(r"<em>.*?</em>", html)
print("Greedy:", greedy)
print("Lazy: ", lazy)
# Detect repeated consecutive words using backreference \1
dup_text = "the the quick brown fox jumps over over the lazy dog"
cleaned = re.sub(r"\b(\w+)\s+\1\b", r"\1", dup_text, flags=re.IGNORECASE)
print("Deduplicated:", cleaned)
# Dynamic replacement using a callback function
def redact_card(match):
digits = match.group(0)
return "XXXX-XXXX-XXXX-" + digits[-4:]
msg = "Card 4532-8891-1024-9981 charged."
print(re.sub(r"\d{4}-\d{4}-\d{4}-\d{4}", redact_card, msg))16.8 Foreign Keys, Relational Joins, and Aggregation in SQLite
Real database applications rarely store all data in a single flat table. Instead, entities are normalized across multiple tables linked by foreign keys. In SQLite, foreign key enforcement is disabled by default for backward compatibility and must be enabled per connection via conn.execute("PRAGMA foreign_keys = ON"). Once enabled, referencing a nonexistent parent primary key raises sqlite3.IntegrityError, preserving referential integrity.
To query combined data across normalized tables, SQL INNER JOIN or LEFT JOIN clauses match foreign keys to primary keys, while aggregate functions (COUNT, AVG, MAX, MIN, SUM) paired with GROUP BY compute summary statistics directly inside the database engine rather than transferring entire tables into Python memory.
16.9 End-to-End Application: Regex Log Parser Persisting to SQLite
Combining regular expressions with database programming enables automated Extract-Transform-Load (ETL) pipelines. In the following complete program, raw server access log lines are parsed using a compiled regex with named groups, validated, inserted into a normalized SQLite database via parameterized batch execution, queried using SQL aggregation, updated, and selectively purged.
import re
import sqlite3
LOG_LINE_RE = re.compile(
r"^(?P<ip>\d+\.\d+\.\d+\.\d+)\s+-\s+"
r"(?P<method>GET|POST|PUT|DELETE)\s+"
r"(?P<path>/\S*)\s+(?P<status>\d{3})quot;
)
raw_logs = [
"192.168.1.10 - GET /api/courses 200",
"192.168.1.14 - POST /api/login 401",
"192.168.1.10 - GET /api/grades 200",
"INVALID LOG ENTRY",
"10.0.0.5 - DELETE /api/session 204"
]
parsed_rows = []
for line in raw_logs:
m = LOG_LINE_RE.match(line)
if m:
parsed_rows.append((m.group("ip"), m.group("method"), m.group("path"), int(m.group("status"))))
with sqlite3.connect(":memory:") as conn:
conn.execute("PRAGMA foreign_keys = ON")
cur = conn.cursor()
cur.execute("""
CREATE TABLE access_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT NOT NULL,
method TEXT NOT NULL,
path TEXT NOT NULL,
status INTEGER NOT NULL
)
""")
# INSERT parsed records
cur.executemany(
"INSERT INTO access_logs (ip, method, path, status) VALUES (?, ?, ?, ?)",
parsed_rows
)
conn.commit()
# READ aggregated counts per HTTP status
cur.execute("SELECT status, COUNT(*) FROM access_logs GROUP BY status ORDER BY status")
print("Status Summary:", cur.fetchall())
# UPDATE status 401 to flagged code 403 for audit
cur.execute("UPDATE access_logs SET status = ? WHERE status = ?", (403, 401))
conn.commit()
# DELETE transient 204 records
cur.execute("DELETE FROM access_logs WHERE status = ?", (204,))
conn.commit()
cur.execute("SELECT id, ip, method, path, status FROM access_logs")
for row in cur.fetchall():
print("Final Row:", row)16.10 Regex Flags, Verbose Patterns, and Match Object Anatomy
When regular expressions grow complex, cramming dense character classes and lookaheads onto a single line harms maintainability. Python's re.VERBOSE (re.X) flag instructs the regex compiler to ignore unescaped whitespace and treat # comments inside the pattern as documentation, enabling multi-line, self-documenting patterns. Other essential flags include re.IGNORECASE (re.I) for case-insensitive matching, re.MULTILINE (re.M) so ^ and $ match the start and end of every line rather than just the entire string, and re.DOTALL (re.S) so the dot metacharacter . matches newline characters as well.
Whenever re.match(), re.search(), or re.finditer() succeeds, it returns a Match object exposing rich positional metadata: m.group(0) returns the entire matched substring, m.groups() returns a tuple of all captured subgroups, m.start() and m.end() return the slice indices, and m.span() returns the (start, end) tuple directly.
import re
URL_RE = re.compile(r"""
^(?P<scheme>https?):// # Protocol scheme
(?P<host>[A-Za-z0-9.-]+) # Domain or IPv4 host
(?::(?P<port>\d+))? # Optional port number
(?P<path>/\S*)?$ # Optional resource path
""", re.VERBOSE | re.IGNORECASE)
sample_url = "HTTPS://degreelive.in:443/bca/semester-4"
m = URL_RE.match(sample_url)
if m:
print("Parsed URL:", m.groupdict())
print("Host span:", m.span("host"), "| Host:", m.group("host"))16.11 Database Indexing, Pagination with fetchmany(), and Relational Joins
As database tables grow from dozens to millions of rows, full table scans during SELECT queries degrade linearly in time. Creating a B-tree index via CREATE INDEX idx_student_dept ON students(dept) allows SQLite or MySQL to locate matching rows in time. Furthermore, calling cur.fetchall() on a massive result set loads every row into Python memory at once; instead, streaming batches via cur.fetchmany(batch_size) keeps memory consumption constant.
To prevent SQL injection when filtering against a dynamic list of values (such as a Python list of roll numbers), generate the exact number of parameter placeholders dynamically (", ".join("?" for _ in ids)) and pass the tuple of values as the second argument to cur.execute().
import sqlite3
with sqlite3.connect(":memory:") as conn:
conn.execute("PRAGMA foreign_keys = ON")
cur = conn.cursor()
cur.execute("CREATE TABLE courses (code TEXT PRIMARY KEY, title TEXT NOT NULL)")
cur.execute("""
CREATE TABLE enrollments (
roll_no INTEGER,
course_code TEXT,
grade TEXT,
PRIMARY KEY (roll_no, course_code),
FOREIGN KEY (course_code) REFERENCES courses(code) ON DELETE CASCADE
)
""")
cur.execute("INSERT INTO courses VALUES (?, ?)", ("UK4DSCCAP203", "Python Programming"))
cur.execute("INSERT INTO courses VALUES (?, ?)", ("UK4DSCCAP204", "Network Security"))
cur.executemany(
"INSERT INTO enrollments VALUES (?, ?, ?)",
[(101, "UK4DSCCAP203", "A+"), (102, "UK4DSCCAP203", "A"), (101, "UK4DSCCAP204", "B+")]
)
conn.commit()
# INNER JOIN query
cur.execute("""
SELECT e.roll_no, c.code, c.title, e.grade
FROM enrollments e
INNER JOIN courses c ON e.course_code = c.code
WHERE e.roll_no = ?
""", (101,))
for r in cur.fetchall():
print("Transcript Row:", r)
# Safe parameterized IN query
target_codes = ["UK4DSCCAP203", "UK4DSCCAP204"]
placeholders = ", ".join("?" for _ in target_codes)
cur.execute(f"SELECT COUNT(*) FROM enrollments WHERE course_code IN ({placeholders})", target_codes)
print("Total matching enrollments:", cur.fetchone()[0])16.12 Word Boundaries, Anchors, and Splitting with Capture Groups
Precise pattern matching often depends on zero-width positional anchors rather than literal characters. The word boundary anchor \b matches the transition between a word character (\w) and a non-word character (\W or string edge), preventing partial-word false positives—for example, r"\bcat\b" matches "the cat sat" without matching "catalog" or "scatter". Similarly, re.split(pattern, text) behaves specially when the delimiter pattern includes a capturing group: Python retains the matched delimiters inside the returned list alongside the split tokens, enabling clean tokenizer pipelines.
import re
sentence = "The catalog lists a black cat and a wildcat."
exact_cats = re.findall(r"\bcat\b", sentence)
print("Exact word matches:", exact_cats)
# Capturing group in re.split preserves delimiters
expr = "12 + 34 - 5 * 2"
tokens = re.split(r"\s*([+\-*/])\s*", expr)
print("Arithmetic tokens:", tokens)16.13 Complete Database-Backed Student Ledger Utility
To consolidate DB-API 2.0 connection management, table creation, parameterized CRUD operations, error handling, and regex input validation, the following complete module implements a reusable StudentLedger class. Each method enforces strict input validation with regular expressions before executing parameterized SQL statements inside explicit transactions, ensuring both data hygiene and ACID durability.
import re
import sqlite3
class StudentLedger:
ROLL_RE = re.compile(r"^UK4\d{3}quot;)
def __init__(self, db_path=":memory:"):
self.conn = sqlite3.connect(db_path)
self.conn.row_factory = sqlite3.Row
self.conn.execute("""
CREATE TABLE IF NOT EXISTS ledger (
roll_code TEXT PRIMARY KEY,
student_name TEXT NOT NULL,
marks REAL NOT NULL
)
""")
self.conn.commit()
def add_student(self, roll_code, name, marks):
if not self.ROLL_RE.match(roll_code):
raise ValueError(f"Invalid roll code: {roll_code}")
self.conn.execute(
"INSERT INTO ledger (roll_code, student_name, marks) VALUES (?, ?, ?)",
(roll_code, name, marks)
)
self.conn.commit()
def update_marks(self, roll_code, new_marks):
cur = self.conn.execute(
"UPDATE ledger SET marks = ? WHERE roll_code = ?",
(new_marks, roll_code)
)
self.conn.commit()
return cur.rowcount
def fetch_all(self):
return [dict(r) for r in self.conn.execute("SELECT * FROM ledger ORDER BY roll_code")]
def delete_student(self, roll_code):
cur = self.conn.execute("DELETE FROM ledger WHERE roll_code = ?", (roll_code,))
self.conn.commit()
return cur.rowcount
def close(self):
self.conn.close()
ledger = StudentLedger()
ledger.add_student("UK4001", "Meera", 89.5)
ledger.add_student("UK4002", "Nikhil", 76.0)
ledger.update_marks("UK4002", 81.5)
print("All records:", ledger.fetch_all())
ledger.delete_student("UK4001")
print("After delete:", ledger.fetch_all())
ledger.close()University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 4 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Python Programming (University of Kerala BCA Sem 4)
Python Programming (UK4DSCCAP203 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in python programming. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Python Programming Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
Introduction to Python
Computing begins with the precise formulation of a computational problem—a well-defined specification that maps a set of valid inputs to a desired set of outputs through a finite sequence of deterministic transformations. Before a single line of Python code is written, a software engineer must analyze the problem domain, identify all constraints, boundary conditions, and data types, and decompose complex requirements into manageable sub-problems.
Data Structures & Type Conversion
A list is an ordered, mutable, heterogeneous sequence capable of storing elements of any data type—including integers, strings, nested lists, or custom objects—within square brackets ( [10, "BCA", 3.14] ). Because lists maintain insertion order and allow duplicate values, they serve as Python's primary general-purpose dynamic array. Internally, CPython implements lists as contiguous arrays of object pointers that automatically over-allocate capacity during growth, ensuring amortized O ( 1 ) append performance.
Flow Control & Functions
Control flow statements determine the runtime execution path of a program based on Boolean conditions. Python uses indentation (four spaces per level by PEP 8 standard) to delimit the body of each branch. The simplest conditional is the if statement, which executes its suite only when its predicate evaluates to truthy. Adding an else clause guarantees mutually exclusive two-way branching, whereas chained elif (else-if) clauses evaluate multiple conditions sequentially from top to bottom and execute only the first matching branch.
Packages, Files, Exception Handling & OOP
A Python module is any file ending in.py that groups related functions, classes, and constants into a reusable unit. Python ships with extensive built-in and standard-library modules such as math, random, os, sys, and datetime. Developers create custom modules simply by saving Python definitions in a file (for instance, geometry.py ) and importing them elsewhere.
Regular Expressions & Database Programming
A regular expression (regex) is a formal pattern string that describes a set of matching character sequences using literal characters combined with special metacharacters. Regular expressions power input validation (emails, phone numbers, course codes), log parsing, lexical analysis, and structured text extraction. Python's standard re module provides a high-performance regex engine. Always write regex patterns using Python raw string literals ( r"\d+\.
Core Curriculum & Key Topics
- Fundamentals of Computing and Algorithmic Problem Solving
- 1 Identification of Computational Problems
- 2 Algorithms: Properties and Design Principles
- 3 Flowcharts and Pseudocode
- Introduction to Python and Execution Modes
- 1 History and Key Features of Python
- 2 The Python Interpreter: Bytecode and the PVM
- 3 Interactive Mode vs. Script Mode
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of python programming.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Python Programming
The evaluation framework for Python Programming (UK4DSCCAP203) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK4DSCCAP203 (Python Programming) examination: 1. Write Clean, Traceable Code Snippets: Always include well-indented syntax examples with sample input and expected output for programming questions. 2. Explain Logic & Control Flow Step-by-Step: Before writing full programs, briefly outline the algorithm, key functions, or class hierarchy so examiners can award full step marks. 3. Highlight Edge Cases & Syntax Rules: Mention common runtime pitfalls, data type constraints, or security/validation practices where relevant. 4. Manage Time Across Sections: For the 2.5-hour 70-mark external paper, allocate 25 minutes to Part A definitions, 50 minutes to Part B short programs and comparisons, and 75 minutes to Part C full code-backed essays.
Exam Preparation & Study Guides — Python Programming
What is Fundamentals of Computing & Computational Problems and why is it important in Python Programming?
Computing begins by specifying a deterministic mapping from valid problem inputs (preconditions) to desired outputs (postconditions) while analyzing boundary cases, time complexity, and memory constraints.
What is Relational & Logical Operators and why is it important in Python Programming?
Comparisons (==,!=, <, >, <=, >=) support chained evaluation (10 <= x <= 20), while short-circuiting logical operators (and, or, not) return one of their actual operands rather than strictly coercing to bool.
What is Tuples (Immutable Ordered Sequences) and why is it important in Python Programming?
Written with parentheses ((10, 20)) or a mandatory trailing comma for singletons ((42,)), tuples represent fixed records, multiple function return values, and immutable dictionary keys.
What is while Loop & Nested Loops and why is it important in Python Programming?
Indefinite pretest loop repeating while condition is truthy (must update loop state toward exit); nested loops process 2D matrices and Cartesian pairs with multiplicative iteration counts.
What is open(), close() & Context Managers and why is it important in Python Programming?
open(path, mode, encoding='utf-8') supports 'r' (read), 'w' (truncate/write), 'a' (append), 'x' (exclusive create), 'r+'/'w+' (read-write), and binary 'rb'/'wb'; with open(...) as f guarantees automatic closure even if exceptions occur.
What is the official course code and credit structure for Python Programming at University of Kerala?
Python Programming carries the official course code UK4DSCCAP203 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Python Programming?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Python Programming (UK4DSCCAP203) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 4 Subjects
Browse study notes for other courses in BCA Sem 4:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.