Review status: Candidate only. TU confirms course identity, but unit outline comes from an unverified third-party source. Do not present it as official TU micro-syllabus. Captured 2026-11-20 from python-programming.

Unit 1: Introduction to Python and Basic Elements (6 hrs)

1.1 What is Python?

Explanation. Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes readability through significant indentation ("the off-side rule") and comes with a rich standard library. The current production version is Python 3; Python 2 reached end of life on 1 January 2020 and should not be used. Python is used for web back-ends, automation scripts, data analysis, scientific computing, and artificial intelligence. A Python program is normally stored in a file ending .py and executed by the Python interpreter, which compiles source to bytecode and runs it on the Python virtual machine.

Worked example.

# hello.py — a complete Python 3 program
print("Hello, BCA254!")
print(21 + 3)          # 24

Run it: python3 hello.py. Output:

Hello, BCA254!
24

Common mistake. Writing print "Hello" (Python 2 statement style) in Python 3 raises SyntaxError; print is a function in Python 3 and requires parentheses. Also, mixing tabs and spaces for indentation raises IndentationError.

Quick self-check. Q: Is Python 2 still supported? A: No — Python 2 ended 2020-01-01; use Python 3. Q: What extension does a Python source file normally use? A: .py.


1.2 Tokens: identifiers, keywords, comments, indentation

Explanation. Tokens are the smallest meaningful units of a Python program. An identifier names a variable, function, class, module, or package: it must start with a letter (a–z, A–Z) or underscore (_), may contain letters, digits, and underscores, is case-sensitive, and cannot be a keyword. Keywords are reserved words with fixed meaning (if, else, while, for, def, class, return, import, True, False, None, and, or, not, in, is, lambda, with, as, try, except, raise, break, continue, pass, global, nonlocal, assert, del, yield, async, await, from, match, case, ...). A comment starts with # and runs to end of line; comments are ignored by the interpreter and document intent. Indentation (spaces or tabs, consistently) groups statements into blocks; Python uses indentation instead of curly braces.

Worked example.

# This line is a comment; it documents what follows
age = 21                # identifier 'age' bound to int object 21
if age >= 18:           # keyword 'if'; colon opens an indented block
    print("adult")      # indented statement — part of the if-block
else:
    print("minor")

Output (age is 21):

adult

Common mistake. Using a keyword as an identifier (class = 5, for = 1) raises SyntaxError. Mixing tabs and spaces in the same block raises IndentationError: unexpected indent. Forgetting the colon after if/else/for/while/def raises SyntaxError.

Quick self-check. Q: Which character starts a one-line comment? A: #. Q: Can for be used as a variable name? A: No — for is a keyword.


1.3 Variables and dynamic typing

Explanation. A variable is a name bound to an object in memory; assignment uses =. Python is dynamically typed: types belong to objects, not names, so the same name can later be bound to an object of a different type. There is no variable declaration. Reading a name before it is bound raises NameError. The built-in id(x) shows an object's identity, and type(x) shows its type.

Worked example.

x = 10          # x now names an int object
print(type(x))  # <class 'int'>
x = "ten"       # legal in Python: x now names a str object (dynamic typing)
print(type(x))  # <class 'str'>
print(y)        # NameError: name 'y' is not defined

Output:

<class 'int'>
<class 'str'>

(then NameError on print(y))

Common mistake. Assuming a variable keeps a declared type forever, or reading an unassigned variable. Since types travel with objects, rebinding is legal; the error only appears when you read a name never assigned.

Quick self-check. Q: What error occurs when you read a name that was never assigned? A: NameError. Q: Is x = 10; x = "hi" legal? A: Yes — dynamic typing allows rebinding to a different type.


1.4 Data types

Explanation. Python's principal built-in types are int (arbitrary-precision integers), float (IEEE-754 double-precision), complex, str (text), bool (True/False; a subclass of int, so True == 1 and False == 0), list, tuple, set, dict, bytes, and NoneType (the single value None). type(value) reports the type. Floats are approximate binary fractions, so 0.1 + 0.2 is not exactly 0.3; never compare floats with == — compare with a small tolerance instead.

Worked example.

pi = 3.14159
flag = True
name = "Asha"
items = None
print(type(pi), type(flag), type(name), type(items))
print(True == 1, False == 0)   # True True
print(0.1 + 0.2 == 0.3)        # False (floats are approximate)
print(abs(0.1 + 0.2 - 0.3) < 1e-9)  # True — tolerance comparison

Output:

<class 'float'> <class 'bool'> <class 'str'> <class 'NoneType'>
True True
False
True

Common mistake. Comparing floats with == (e.g., 0.1 + 0.2 == 0.3) is False due to binary representation; always use a tolerance such as abs(a - b) < 1e-9.

Quick self-check. Q: What does type(True) return? A: <class 'bool'>. Q: Is bool a subclass of int? A: Yes — True == 1.


1.5 Operators

Explanation. Python operators include arithmetic (+, -, *, /, //, %, **), comparison (==, !=, <, >, <=, >=), logical (and, or, not), assignment (=, +=, -=, *=, /=, //=, %=, **=), identity (is, is not), membership (in, not in), and bitwise (&, |, ^, ~, <<, >>). Precedence (high to low): parentheses, **, unary +/-, *//////%, +/-, comparisons, not, and, or. / always returns a float in Python 3; // is floor division (rounds toward negative infinity).

Worked example.

a, b = 10, 3
print(a // b, a % b, a ** 2)        # 3 1 100
print(10 > 5 and 3 < 4)             # True
print(10 > 5 or 3 > 4)              # True
print(not (10 > 5))                 # False
print("a" in "banana")              # True
print(5 is 5, [] is [])             # True False

Output:

3 1 100
True
True
False
True
True False

Common mistake. 7 // -2 equals -4 (floor toward negative infinity), not -3. Also 5 is 5 can be True due to small-integer caching, but is compares identity, not equality — use == for value comparison.

Quick self-check. Q: What is 7 // 2? A: 3. Q: Is and higher precedence than or? A: Yes.


1.6 Type conversion

Explanation. Type conversion changes a value from one type to another. Implicit conversion (coercion) happens automatically, e.g. int + float yields float. Explicit conversion uses constructors: int(), float(), str(), bool(), list(), tuple(), set(), dict(). Conversion can fail when the value is not convertible: int("abc") raises ValueError; int("42.5") also raises ValueError even though the string looks numeric — convert via int(float("42.5")) → 42. bool() treats empty collections, 0, 0.0, "", and None as False; everything else as True.

Worked example.

s = "42"
n = int(s)          # 42
print(n + 8)        # 50
f = float(n)        # 42.0
print(str(f))       # "42.0"
print(int(float("42.5")))   # 42
print(bool([]), bool([1]))   # False True

Output:

50
42.0
42
False True

Common mistake. int("42.5") raises ValueError; you must go through float() first. Also float("abc") raises ValueError; validate input with try/except before converting user input.

Quick self-check. Q: What does int("42.5") do? A: Raises ValueError; use int(float("42.5")) → 42. Q: Is bool(0) true or false? A: False.


1.7 Console input and output

Explanation. print(*objects, sep=' ', end='\n') writes arguments to standard output, separated by sep and ending with end. input(prompt) reads one line from standard input and always returns a string, even if the user typed a number; convert with int()/float() as needed. f-strings (f"...") embed expressions in output: f"age is {age}". input() raises EOFError if the input stream ends (e.g., piped input exhausted).

Worked example.

name = input("Enter your name: ")   # user types Asha
age = int(input("Enter your age: ")) # user types 21
print(f"Hello {name}, next year you will be {age + 1}")
print("a", "b", "c", sep="-", end="!\n")

Sample output:

Enter your name: Asha
Enter your age: 21
Hello Asha, next year you will be 22
a-b-c!

Common mistake. Forgetting that input() returns str and doing arithmetic directly (age + 1 where age is "21") raises TypeError: can only concatenate str (not "int") to str. Always wrap numeric input in int()/float().

Quick self-check. Q: What type does input() return? A: str. Q: What does f"x={2+3}" produce? A: "x=5".


1.8 Useful built-in functions

Explanation. Built-in functions are available without importing anything. Frequently used ones: print(), input(), len(x) (number of items), type(x), int(), float(), str(), bool(), sum(iterable), min(), max(), abs(x), round(x, n), pow(x, y), range(...), enumerate(iterable), zip(...), sorted(iterable), reversed(iterable), help(x), dir(x), id(x). len() works only on sized containers (strings, lists, tuples, dicts, sets); len(5) raises TypeError.

Worked example.

nums = [3, 1, 4, 1, 5]
print(len(nums), sum(nums), min(nums), max(nums))   # 5 14 1 5
print(round(3.14159, 2))                            # 3.14
print(sorted(nums))                                 # [1, 1, 3, 4, 5]
print(list(enumerate(nums)))                        # [(0, 3), (1, 1), ...]

Output:

5 14 1 5
3.14
[1, 1, 3, 4, 5]
[(0, 3), (1, 1), (2, 4), (3, 1), (4, 5)]

Common mistake. Calling len() on a number (len(5)) raises TypeError: object of type 'int' has no len(). Also sum() on mixed types (sum([1, "a"])) raises TypeError.

Quick self-check. Q: What does len("abc") return? A: 3. Q: Does len(5) work? A: No — raises TypeError.


1.9 Seeing the ideas: the people, the machines and the path of a program

Explanation. This is a conceptual topic tying together how software runs. People write source code in .py files using an editor. Machines store and run it: the CPU executes machine code, RAM holds the running program, and storage holds files. The path of a Python program: source code (.py) → compiled to bytecode (stored in .pyc files in __pycache__) → executed by the Python virtual machine (the interpreter, e.g. CPython, the reference implementation) → bytecode interacts with the OS and hardware. Python is often described as "interpreted" but it is really compiled-to-bytecode-then-interpreted, not line-by-line straight from source.

Common mistake. Believing Python is purely interpreted directly from source code line by line; in reality source is compiled to bytecode first, then the VM executes bytecode.

Quick self-check. Q: What file extension holds compiled Python bytecode? A: .pyc (in __pycache__). Q: Is CPython the reference implementation of Python? A: Yes.


Unit 1 key terms

Python 3, interpreter, source code, bytecode, .py, .pyc, token, identifier, keyword, comment, indentation, block, variable, dynamic typing, object, NameError, type(), built-in types (int, float, str, bool, None), operator, precedence, floor division //, implicit conversion, explicit conversion, ValueError, input(), print(), f-string, EOFError, built-in function, len(), sum(), min(), max(), sorted(), tolerance comparison.

Unit 1 summary

Unit 1 establishes the ground rules: Python 3 source is compiled to bytecode and run by the virtual machine; programs consist of tokens arranged in indentation-defined blocks; variables are names bound to typed objects with dynamic typing; built-in types include int, float, str, bool; operators follow a strict precedence; conversion between types is explicit and can raise ValueError; input() returns strings that must be converted for math; print() and f-strings produce output; and a library of built-in functions (len, sum, min, max, sorted, ...) handles everyday tasks. Floating-point values are approximate and must be compared with a tolerance.

Unit 2: Control Flow (5 hrs)

2.1 Conditional statements

Explanation. Conditionals choose among alternatives. Python uses if, elif (else if), and else; each condition is a Boolean expression built from comparison operators (==, !=, <, >, <=, >=) and logical operators (and, or, not). Every value has a truthiness: False, None, 0, 0.0, "", [], {}, set() are falsy; everything else is truthy. Python 3.10+ adds match/case structural pattern matching. Only the first true branch executes; else runs when no condition matched. Indentation defines each branch's block.

Worked example.

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D"
print(grade)                     # B
day = "Monday"
match day:
    case "Monday":
        print("start of week")
    case _:
        print("other day")

Output:

B
start of week

Common mistake. Writing = (assignment) instead of == (equality) in a condition raises SyntaxError; forgetting elif and stacking independent ifs means several branches can run instead of exactly one.

Quick self-check. Q: Is [] truthy or falsy? A: Falsy. Q: Can more than one elif branch run? A: No — only the first true branch.


2.2 The while loop

Explanation. A while loop repeats its body while a condition stays true: while condition:. It is ideal when the number of repetitions isn't known in advance. If the condition never becomes false, the loop runs forever (infinite loop); always ensure the body changes a variable tested by the condition. A while loop can have an else clause that runs when the condition becomes false — but not when the loop exits via break.

Worked example.

n = 5
total = 0
while n > 0:
    total += n
    n -= 1
print(total)                     # 15

# while-else (no break)
n = 3
while n > 0:
    print(n)
    n -= 1
else:
    print("done")

Output:

15
3
2
1
done

Common mistake. Forgetting to update the loop variable (n -= 1) creates an infinite loop; expecting while-else to run after break — it does not.

Quick self-check. Q: Does while-else run after break? A: No — only when the condition becomes false. Q: What happens if the condition never becomes false? A: Infinite loop.


2.3 The for loop and range

Explanation. A for loop iterates over any iterable (string, list, tuple, range, ...): for item in iterable:. It is preferred when the number of items is known or when looping over a container. range(start, stop, step) produces an integer sequence from start up to but excluding stop, incrementing by step (default start=0, step=1). range is lazy — it computes values on demand. A for loop can also have an else clause that runs after the loop finishes normally (no break).

Worked example.

for i in range(5):
    print(i, end=" ")
print()
print(list(range(1, 10, 2)))     # [1, 3, 5, 7, 9]
for ch in "ABC":
    print(ch)

Output:

0 1 2 3 4 
[1, 3, 5, 7, 9]
A
B
C

Common mistake. range(5) yields 0..4, not 1..5 — an off-by-one error. Also range excludes stop; to include stop, write range(start, stop+1).

Quick self-check. Q: What does range(3) produce? A: 0, 1, 2. Q: Does range(1, 5) include 5? A: No — it yields 1, 2, 3, 4.


2.4 break, continue, pass and loop else

Explanation. break exits the loop immediately. continue skips the rest of the current iteration and starts the next one. pass does nothing — a placeholder where syntax requires a statement but no action is needed. Loop else (on while or for) runs when the loop completes without break; it is skipped if break was used. These tools fine-tune iteration: break for early exit once a target is found, continue to filter items, pass for stubs.

Worked example.

for i in range(1, 6):
    if i == 3:
        continue                 # skip 3
    if i == 5:
        break                    # stop at 5
    print(i)
else:
    print("finished normally")   # not printed because of break
print("loop ended")

Output:

1
2
4
loop ended

Common mistake. Confusing continue (next iteration) with break (exit entirely); expecting loop else to run after break.

Quick self-check. Q: Does continue exit the whole loop? A: No — it skips to the next iteration. Q: Does loop else run after break? A: No.


2.5 Nested loops and patterns

Explanation. A nested loop is a loop inside another loop. For each iteration of the outer loop, the inner loop runs to completion. Nested loops are used for multi-dimensional data (rows/columns) and pattern printing. Cost is the product of the two sizes — an outer loop of m and inner loop of n runs the inner body m×n times, so deeply nested loops can be slow. Variables in the inner scope can shadow outer names; use distinct names to avoid confusion.

Worked example.

# right-triangle pattern of stars
rows = 4
for r in range(1, rows + 1):
    for c in range(r):
        print("*", end="")
    print()                      # new line after each row

Output:

*
**
***
****

Common mistake. Forgetting print() (new line) after the inner loop, which prints everything on one line; miscounting range bounds producing off-by-one pattern sizes.

Quick self-check. Q: If outer runs 3 times and inner 4 times, how many times does the inner body run? A: 12 (3×4). Q: What prints a newline after each row in the star pattern? A: print().


2.6 Classic programs

Explanation. Classic small programs combine the constructs above into algorithms: primality testing (check divisors up to √n), greatest common divisor via Euclid's algorithm (while b: a, b = b, a % b), factorial (n! = 1×2×...×n), Fibonacci (each number is the sum of the previous two), and digit sums (sum(int(d) for d in str(n))). These are short loops that recur in exams and labs. Trace them by hand with small inputs to verify correctness.

Worked example.

# Euclidean GCD
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
print(gcd(48, 18))               # 6

# factorial
fact = 1
for i in range(1, 6):
    fact *= i
print(fact)                      # 120

Output:

6
120

Common mistake. GCD with a % b when b is 0 raises ZeroDivisionError — the while b: guard prevents it. Factorial of 0 is 1 by convention; an empty range(1, 1) would skip the loop leaving fact = 1, which is correct.

Quick self-check. Q: What is gcd(48, 18)? A: 6. Q: What is 0!? A: 1.


2.7 Common mistakes

Explanation. This topic consolidates frequent control-flow errors: (1) off-by-one in range — range(n) gives 0..n-1; (2) infinite while loops from never updating the condition variable; (3) = vs == in conditions (SyntaxError); (4) modifying a list while iterating over it — iterate over a copy (for x in lst[:]) or build a new list; (5) expecting loop else after break — it does not run; (6) continue skipping more than intended; (7) unreachable code after return/break; (8) deep nesting harming readability — prefer early returns/guards.

Worked example.

# BAD: modifying while iterating skips items
nums = [1, 2, 3, 4, 5]
for x in nums:
    if x % 2 == 0:
        nums.remove(x)           # skips 4!
print(nums)                      # [1, 3, 5]

# GOOD: build a new list
nums = [1, 2, 3, 4, 5]
odds = [x for x in nums if x % 2 != 0]
print(odds)                      # [1, 3, 5]

Output:

[1, 3, 5]
[1, 3, 5]

Common mistake. nums.remove(x) inside for x in nums shifts indices and skips elements (4 was skipped above). Build a new list or iterate over nums[:].

Quick self-check. Q: Does range(5) include 5? A: No (0..4). Q: Is it safe to remove items from a list while iterating it? A: No — use a copy or build a new list.


2.8 Seeing the ideas: choices, loops and a very long trip

Explanation. Conceptual summary: a program is a sequence of choices (conditionals), repetitions (loops), and steps (statements). Choices let the program react to data; loops let a few lines handle many items; together they express any algorithm. The "very long trip" metaphor: each loop iteration is one step, the condition decides whether to continue, break ends the trip early, and continue skips a leg. Structured control flow (single entry/exit blocks) makes programs easier to trace and debug than unstructured jumps.

Common mistake. Thinking every problem needs its own new construct — most programs are combinations of sequence, selection, and iteration.

Quick self-check. Q: What are the three basic control structures? A: Sequence, selection (if/else), iteration (loops). Q: What does break do inside a loop? A: Exits the loop immediately.


Unit 2 key terms

conditional, if, elif, else, match, case, truthy, falsy, comparison operator, logical operator, while loop, infinite loop, while-else, for loop, iterable, range(start, stop, step), lazy, break, continue, pass, loop else, nested loop, pattern printing, primality, Euclid's GCD, factorial, Fibonacci, digit sum, off-by-one, shadowing, guard clause.

Unit 2 summary

Unit 2 teaches how programs choose and repeat. if/elif/else select one branch using Boolean conditions; match/case (3.10+) matches structure. while repeats while a condition is true (risk of infinite loops); for iterates over iterables with range generating integer sequences (range(n) is 0..n-1). break, continue, pass, and loop else fine-tune loops; nested loops cost the product of sizes and build patterns; classic programs (primes, GCD, factorial, Fibonacci, digit sums) are small loops worth tracing by hand. Common errors: off-by-one range, infinite while, = vs ==, modifying a list during iteration, and else after break.

Unit 3: Strings and Built-in Data Structures (7 hrs)

3.1 Strings

Explanation. Strings (str) are immutable sequences of Unicode characters in Python 3. Indexing s[i] gets the character at position i (0-based; negative indexes from the end). Slicing s[start:stop:step] extracts a substring — stop is exclusive, omitted start/stop default to beginning/end, and negative step reverses. Strings cannot be changed in place (s[0] = "x" raises TypeError); create a new string instead. Common methods: upper(), lower(), strip(), replace(old, new), split(sep), join(iterable), find(sub), startswith(), endswith(). Escape sequences: \n, \t, \\, \', \". Raw strings r"..." treat backslashes literally (useful for paths/regex). f-strings embed expressions.

Worked example.

s = "  Python  "
print(s.strip())                 # "Python"
print(s[0], s[-1], s[2:5])       #     Pyt
print(s[::-1])                   # "  nohtyP" reversed
print("-".join(["a", "b", "c"])) # a-b-c
print("2024-01-15".split("-"))   # ['2024', '01', '15']
try:
    s[0] = "J"
except TypeError as e:
    print("TypeError:", e)

Output:

Python
    Pyt
  nohtyP
a-b-c
['2024', '01', '15']
TypeError: 'str' object does not support item assignment

Common mistake. Trying to mutate a string (s[0] = ...) — strings are immutable; assign a new string to the name instead. Also split() with no argument splits on any whitespace and drops empties; split(" ") splits on single spaces only.

Quick self-check. Q: Are strings mutable in Python? A: No — s[0] = "x" raises TypeError. Q: What does "abc"[::-1] return? A: "cba".


3.2 Lists

Explanation. Lists (list) are ordered, mutable, heterogeneous sequences — Python's general-purpose container. Create with [] or list(). Methods: append(x) (add at end), insert(i, x), pop() (remove and return last, or pop(i)), remove(x) (remove first matching value), clear(), sort() (in place), reverse() (in place), index(x), count(x). sorted(list) and reversed(list) return new objects without mutating. List comprehensions build lists concisely: [expr for item in iterable if cond]. Copies are shallow: new = old binds the same list; use new = old.copy() or new = list(old) for a shallow copy; nested lists need copy.deepcopy() for a deep copy.

Worked example.

nums = [3, 1, 4]
nums.append(2)            # [3, 1, 4, 2]
nums.sort()               # [1, 2, 3, 4]
print(nums.pop())         # 4, nums is now [1, 2, 3]
squares = [x*x for x in range(5)]
print(squares)            # [0, 1, 4, 9, 16]
a = [1, 2]
b = a                     # same object
b.append(3)
print(a)                  # [1, 2, 3] — a changed too (shallow bind)
c = a.copy()
c.append(4)
print(a)                  # [1, 2, 3] — unaffected by c

Output:

4
[0, 1, 4, 9, 16]
[1, 2, 3]
[1, 2, 3]

Common mistake. b = a does not copy — both names refer to one list, so mutating one mutates the other. Use .copy() / list() for a shallow copy, and copy.deepcopy() when the list contains other mutable objects.

Quick self-check. Q: Does b = a copy a list? A: No — both names bind the same list object. Q: What does [x*x for x in range(3)] produce? A: [0, 1, 4].


3.3 Tuples

Explanation. Tuples (tuple) are ordered, immutable, heterogeneous sequences — fixed records. Create with (1, 2) or tuple(); a singleton needs a trailing comma (x,) (otherwise parentheses just group). Tuples support indexing, slicing, len(), count(), index(). Because they are immutable and hashable (if elements are hashable), tuples can be dictionary keys and set elements — lists cannot. Tuple unpacking assigns a tuple to multiple names: a, b = (1, 2). zip() produces tuples.

Worked example.

point = (3, 4)            # fixed record: x, y
x, y = point              # unpacking
print(x, y)               # 3 4
singleton = (7,)          # tuple with one element
print(type(singleton), type((7)))  # <class 'tuple'> <class 'int'>
d = {(0, 0): "origin"}    # tuple as dict key — legal
print(d[(0, 0)])          # origin
try:
    point[0] = 5
except TypeError as e:
    print("TypeError:", e)

Output:

3 4
<class 'tuple'> <class 'int'>
origin
TypeError: 'tuple' object does not support item assignment

Common mistake. Writing (7) instead of (7,) — parentheses without a comma are just grouping, so (7) is an int, not a tuple. Also attempting point[0] = 5 raises TypeError (immutable).

Quick self-check. Q: Is (7) a tuple? A: No — it's an int; use (7,). Q: Can a tuple be a dictionary key? A: Yes, if its elements are hashable.


3.4 Sets

Explanation. Sets (set) are unordered collections of unique, hashable elements — mathematical sets. Create with {1, 2, 3} or set(). They give O(1) average membership testing (x in s) and automatic deduplication. Methods: add(x), remove(x) (raises KeyError if missing), discard(x) (no error if missing), pop(), clear(). Set operations: | union, & intersection, - difference, ^ symmetric difference; <, >, <=, >= test subset/superset. Sets cannot contain unhashable items (lists, dicts, other sets). Because sets are unordered, indexing s[0] raises TypeError.

Worked example.

a = {1, 2, 3, 3}          # {1, 2, 3} — duplicate removed
b = {3, 4, 5}
print(a | b)              # {1, 2, 3, 4, 5} union
print(a & b)              # {3} intersection
print(a - b)              # {1, 2} difference
print(a ^ b)              # {1, 2, 4, 5} symmetric difference
a.add(4)
a.remove(2)
print(a)                  # {1, 3, 4}
print(3 in a)             # True
try:
    a[0]
except TypeError as e:
    print("TypeError:", e)

Output:

{1, 2, 3, 4, 5}
{3}
{1, 2}
{1, 2, 4, 5}
{1, 3, 4}
True
TypeError: 'set' object is not subscriptable

Common mistake. Indexing a set (s[0]) — sets are unordered and not subscriptable; iterate over them instead. Also remove(x) raises KeyError if x is absent; use discard(x) when absence is acceptable.

Quick self-check. Q: Is {1, 2, 2} equal to {1, 2}? A: Yes — duplicates removed. Q: Can you index a set with s[0]? A: No — raises TypeError.


3.5 Dictionaries

Explanation. Dictionaries (dict) are mutable mappings of hashable keys to values — key-based lookup in O(1) average. Create with {} or dict(). Keys must be immutable/hashable (str, int, tuple of hashables — not lists). Values can be any type. Operations: d[key] (get, raises KeyError if missing), d.get(key, default) (safe, returns default), d[key] = value (add/update), del d[key], d.pop(key, default), d.keys(), d.values(), d.items(), d.update(other), d.clear(). Since Python 3.7, dicts preserve insertion order. Use get() when a key might be missing; use in to test membership (key in d).

Worked example.

phone = {"Asha": 9801111111, "Binod": 9801222222}
print(phone["Asha"])                   # 9801111111
print(phone.get("Carl", "not found"))  # not found (safe)
phone["Asha"] = 9801333333             # update
phone["Deepa"] = 9801444444            # add
print("Binod" in phone)                # True
print(phone.keys())                    # dict_keys([...])
for k, v in phone.items():
    print(k, "->", v)

Output:

9801111111
not found
True
dict_keys(['Asha', 'Binod', 'Deepa'])
Asha -> 9801333333
Binod -> 9801222222
Deepa -> 9801444444

Common mistake. phone["Missing"] raises KeyError; use phone.get("Missing") or phone.get("Missing", default). Also using a list as a key ({[1,2]: 3}) raises TypeError: unhashable type: 'list'.

Quick self-check. Q: What does d.get("missing", 0) return if "missing" is absent? A: 0. Q: Can a list be a dictionary key? A: No — lists are unhashable.


3.6 Choosing a data structure

Explanation. Pick the container by what you need: use a list for an ordered, mutable sequence where duplicates and position matter; a tuple for fixed records or when you need a hashable key; a set for uniqueness, fast membership, or set operations (union/intersection); a dict for key-based lookup or grouping related attributes. Strings for text. Use a list comprehension to build lists, a generator expression when you only need to iterate once (saves memory), and collections alternatives (Counter, defaultdict, deque, namedtuple) for specialized cases. Consider mutation: choose immutable (tuple) when data should not change accidentally.

Worked example.

# Decision sketch
names = ["Asha", "Binod"]          # list: ordered, may grow
point = (0, 0)                     # tuple: fixed coordinate, hashable
unique_ids = {101, 102, 103}       # set: unique, fast "in"
contact = {"Asha": "9801..."}      # dict: name -> number

Choose by query type: "is x present?" → set; "value for key k?" → dict; "keep order and duplicates?" → list; "fixed record / dict key?" → tuple.

Common mistake. Using a list when you only need membership tests (O(n) vs O(1) for sets), or mutating a tuple-containing structure expecting immutability to protect nested lists (tuple is shallow-immutable: t = ([1], 2); t[0].append(3) works).

Quick self-check. Q: For fast "is x present?" tests, which container? A: set. Q: Which container preserves key→value mapping? A: dict.


3.7 Seeing the ideas: text, code points and four containers

Explanation. Conceptual synthesis: text is strings — sequences of Unicode code points, where slicing and methods manipulate text without mutating it. The four containers each answer a different question: lists answer "an ordered, changeable collection", tuples answer "a fixed record", sets answer "which items are present (uniquely, fast)", and dictionaries answer "what value belongs to this key". Immutability (str, tuple) means safety and hashability; mutability (list, set, dict) means flexibility. Choosing well makes code clearer, faster, and less error-prone.

Common mistake. Believing immutability means "can never change" for a tuple holding a list — the tuple can't replace its items, but a mutable item inside can still change in place.

Quick self-check. Q: Which two built-in containers are immutable? A: str and tuple (also bytes, frozenset). Q: Does tuple immutability protect a list stored inside it? A: No — the inner list can still mutate.


Unit 3 key terms

str, Unicode, code point, indexing, slicing, immutable, escape sequence, raw string, f-string, strip(), replace(), split(), join(), find(), list, mutable, heterogeneous, append(), pop(), remove(), sort(), reverse(), list comprehension, shallow copy, deep copy, copy.deepcopy(), tuple, singleton tuple (x,), unpacking, hashable, dict key, set, unique, membership, add(), remove(), discard(), union |, intersection &, difference -, symmetric difference ^, dict, mapping, get(), keys(), values(), items(), O(1), choosing a container.

Unit 3 summary

Unit 3 covers text and containers. Strings are immutable Unicode sequences accessed by indexing/slicing and manipulated with methods (strip, replace, split, join, find) and f-strings. Lists are ordered mutable sequences with append/pop/sort and comprehensions; copies are shallow unless deep-copied. Tuples are immutable fixed records that can serve as dict keys. Sets store unique hashable items with O(1) membership and set operators. Dictionaries map hashable keys to values with safe access via get(). Choose the container by the question you ask: membership → set, key lookup → dict, ordered changeable collection → list, fixed record → tuple.

Unit 4: Functions, Modules and Packages (7 hrs)

4.1 Defining and calling functions

Explanation. A function is a named, reusable block of code defined with def name(parameters): and an indented body. It runs only when called: name(arguments). Parameters are the variables in the definition; arguments are the values passed at the call. Functions may have default parameters (def f(a=10):), keyword arguments (f(a=5)), positional arguments, and return value (returns None if no return statement). Parameters are local to the function. Functions are first-class objects: they can be assigned, passed, and returned.

Worked example.

def greet(name, greeting="Hello"):
    """Return a greeting string."""
    return f"{greeting}, {name}!"

print(greet("Asha"))                  # Hello, Asha!
print(greet("Binod", "Hi"))           # Hi, Binod!
print(greet(name="Deepa"))            # Hello, Deepa! (keyword argument)
result = greet
print(result("Carl", "Hey"))          # Hey, Carl! (function as object)

Output:

Hello, Asha!
Hi, Binod!
Hello, Deepa!
Hey, Carl!

Common mistake. Forgetting return means the function returns None; mutable default arguments (def f(items=[])) are shared across calls — use None default and create inside: def f(items=None): if items is None: items = [].

Quick self-check. Q: What does a function with no return statement return? A: None. Q: Are arguments positional or keyword? A: Either — f(5) positional, f(a=5) keyword.


4.2 Scope: the LEGB rule

Explanation. LEGB is the order Python searches names: Local (inside current function), Enclosing (nested functions), Global (module level), Built-in (preloaded names like len, print). Assignment inside a function creates a local name unless declared global (module level) or nonlocal (nearest enclosing function). A name is resolved at call time by searching LEGB in order; if not found anywhere, NameError. The global keyword rebinds a module-level name; nonlocal rebinds a name in an enclosing function.

Worked example.

x = "global"                          # G
def outer():
    x = "enclosing"                   # E
    def inner():
        nonlocal x                    # rebind E's x
        x = "enclosing changed"
        print("inner:", x)            # L
    inner()
    print("outer:", x)
outer()
print("global:", x)                   # G unchanged

Output:

inner: enclosing changed
outer: enclosing changed
global: global

Common mistake. Assuming x = 1 inside a function changes a module-level x — it creates a local x instead; use global x to rebind module level. Forgetting nonlocal in nested functions means the inner assignment creates a new local, leaving the enclosing variable unchanged.

Quick self-check. Q: What does LEGB stand for? A: Local, Enclosing, Global, Built-in. Q: Does x = 1 inside a function change module-level x? A: No — use global x.


4.3 Recursion

Explanation. Recursion is a function calling itself to solve a smaller instance of the same problem. Every recursive function needs a base case (condition that stops, returns directly) and a recursive case (calls itself with a smaller/simpler input, progressing toward the base case). Without a base case, or if input doesn't shrink, recursion never ends → RecursionError: maximum recursion depth exceeded. Python's default recursion limit (~1000) can be checked/changed with sys.getrecursionlimit()/setrecursionlimit(). Recursion suits tree-like problems (factorial, Fibonacci, file-system traversal) but iteration is often simpler and faster in Python.

Worked example.

def factorial(n):
    if n <= 1:                        # base case
        return 1
    return n * factorial(n - 1)       # recursive case, n shrinks

print(factorial(0))                   # 1
print(factorial(5))                   # 120
# Trace factorial(3): 3*factorial(2) → 3*2*factorial(1) → 3*2*1 = 6

Output:

1
120

Common mistake. Missing or unreachable base case → infinite recursion → RecursionError. Also computing Fibonacci naively by recursion repeats work exponentially; use memoization or iteration.

Quick self-check. Q: What happens without a base case? A: RecursionError (infinite recursion). Q: What is factorial(0)? A: 1.


4.4 Anonymous functions and functional tools

Explanation. lambda args: expression creates an anonymous (unnamed) function with a single expression; it's handy for short throwaway functions, e.g. key functions in sorting. Functional tools: map(func, iterable) applies func to each item; filter(func, iterable) keeps items where func is true; sorted(iterable, key=func) orders by key result. These return iterators (map/filter) in Python 3 — wrap in list() to see results. List comprehensions are often more readable than map/filter.

Worked example.

nums = [1, 2, 3, 4, 5]
square = lambda x: x * x
print(square(4))                      # 16
print(list(map(square, nums)))        # [1, 4, 9, 16, 25]
print(list(filter(lambda x: x % 2 == 0, nums)))  # [2, 4]
words = ["banana", "apple", "cherry"]
print(sorted(words, key=len))         # ['apple', 'banana', 'cherry']
print(sorted(nums, key=lambda x: -x)) # [5, 4, 3, 2, 1]

Output:

16
[1, 4, 9, 16, 25]
[2, 4]
['apple', 'banana', 'cherry']
[5, 4, 3, 2, 1]

Common mistake. map/filter return iterators, not lists — printing them shows a map object; wrap in list(). A lambda holds one expression only (no statements, no return keyword — the expression value is returned automatically).

Quick self-check. Q: Do map and filter return lists in Python 3? A: No — they return iterators; use list(...). Q: Can a lambda contain multiple statements? A: No — single expression only.


4.5 Closures, decorators and generators

Explanation. A closure is a nested function that remembers variables from its enclosing scope even after the outer function returns. A decorator is a callable that takes a function and returns a (usually wrapped) function, applied with @decorator above def — used for logging, timing, access control, registration. A generator is a function with yield that produces a sequence lazily, one item at a time, preserving state between calls; it returns a generator object and raises StopIteration when exhausted. Generators save memory for large/infinite streams.

Worked example.

# closure
def make_multiplier(factor):
    def multiply(n):
        return n * factor           # remembers 'factor'
    return multiply
times3 = make_multiplier(3)
print(times3(4))                      # 12

# decorator
def log(func):
    def wrapper(*args, **kwargs):
        print("calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper
@log
def say(name):
    return f"hi {name}"
print(say("Asha"))

# generator
def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1
print(list(count_up_to(3)))           # [1, 2, 3]

Output:

12
calling say
hi Asha
[1, 2, 3]

Common mistake. A decorator without return func(...) swallows the return value of the decorated function. Generators execute lazily — the body runs only as you iterate; code before the first yield runs on first next().

Quick self-check. Q: What does yield do? A: Produces one value and pauses; resumes on next iteration. Q: When does a generator body start running? A: On first iteration/next(), not at definition.


4.6 Modules and packages

Explanation. A module is a .py file; import it with import math or from math import sqrt. A package is a directory of modules with an __init__.py (traditionally; optional in Python 3.3+ namespace packages), imported as import package.module. import runs the module and binds its name; from ... import * is discouraged. dir(module) lists names; help(module) documents. The standard library (math, random, datetime, pathlib, json, csv, sqlite3, os, sys, ...) covers most everyday tasks. Third-party packages install via pip into virtual environments.

Worked example.

import math
import random
from datetime import date
print(math.sqrt(16))                  # 4.0
print(random.randint(1, 6))           # random 1..6
print(date.today())                   # current date
import os
print(os.getcwd())                    # current working directory

Output (example):

4.0
4
2026-11-20
/Users/.../project

Common mistake. from math import * pollutes the namespace and hides where names came — prefer explicit imports. Circular imports (a imports b, b imports a) can cause ImportError; restructure or move shared code to a third module.

Quick self-check. Q: Is from math import * recommended? A: No — use explicit imports. Q: What file traditionally marks a package directory? A: __init__.py.


4.7 Seeing the ideas: bricks, scopes and the call stack

Explanation. Conceptual synthesis: functions are bricks — named, reusable pieces that take input and return output. Scopes (LEGB) decide which brick a name belongs to and how long it lives. The call stack tracks active function calls: each call pushes a frame (local variables, return address); returning pops it. Recursion builds a deep stack; each recursive call is its own frame. Closures and decorators extend functions with memory and wrapping; generators pause frames mid-execution. Modules/packages group bricks into libraries. Together they let you write programs as small, independent, testable pieces rather than one long script.

Common mistake. Thinking each function call shares one set of variables — every call gets its own local frame, which is why recursion works.

Quick self-check. Q: What is a function "brick"? A: A named reusable block taking input and returning output. Q: What does the call stack track? A: Active function calls and their local frames.


Unit 4 key terms

def, function, parameter, argument, return, None, default parameter, keyword argument, first-class object, scope, LEGB, Local, Enclosing, Global, Built-in, global, nonlocal, NameError, recursion, base case, recursive case, RecursionError, sys.getrecursionlimit, lambda, anonymous function, map, filter, sorted, key, iterator, closure, decorator, @, wrapper, generator, yield, lazy, StopIteration, module, .py, package, __init__.py, import, from ... import, standard library, pip, virtual environment, call stack, frame.

Unit 4 summary

Unit 4 teaches structuring code into reusable pieces. Functions (def) take parameters and return values; default and keyword arguments add flexibility. LEGB (Local, Enclosing, Global, Built-in) governs name lookup; global/nonlocal rebind names in outer scopes. Recursion solves problems via self-calls with a base case; watch for RecursionError. lambda makes anonymous functions; map, filter, and sorted(key=...) are functional tools returning iterators. Closures remember enclosing variables; decorators (@) wrap functions; generators (yield) produce lazy sequences. Modules are .py files, packages are directories; the standard library covers most tasks and pip installs third-party packages into virtual environments.

Unit 5: File Handling and Exception Handling (6 hrs)

5.1 Text files

Explanation. Text files store human-readable characters. Open with open(path, mode) where modes include "r" (read), "w" (write, truncates), "a" (append), "x" (exclusive creation). Always use with open(...) as f: — the context manager closes the file automatically even if an error occurs. Read lazily by iteration (for line in f:), f.read() (all), f.readline() (one line), f.readlines() (list). Write with f.write(text); add \n explicitly for newlines. pathlib.Path handles paths in an OS-independent way. Text encoding defaults to platform encoding; specify encoding="utf-8" for portability.

Worked example.

from pathlib import Path
p = Path("notes.txt")
p.write_text("line one\nline two\n", encoding="utf-8")   # write
with p.open("r", encoding="utf-8") as f:
    for line in f:                                       # lazy iteration
        print(line.rstrip("\n"))
# Output:
# line one
# line two
print(p.read_text(encoding="utf-8").count("line"))       # 2
p.unlink()                                               # delete

Common mistake. Forgetting with and not closing the file (resource leak, data not flushed); writing with "w" truncates existing content; assuming \n is added by write() — it isn't.

Quick self-check. Q: Why use with open(...)? A: It closes the file automatically, even on errors. Q: Does f.write("hi") add a newline? A: No — add \n explicitly.


5.2 CSV and JSON

Explanation. CSV (comma-separated values) stores tables as text rows; Python's csv module reads/writes with csv.reader, csv.writer, csv.DictReader, csv.DictWriter. JSON (JavaScript Object Notation) stores nested data as objects/arrays; Python's json module: json.dump(obj, f) writes to file, json.load(f) reads, json.dumps()/json.loads() work on strings. JSON maps to Python: object→dict, array→list, string→str, number→int/float, true→True, false→False, null→None. Use with for both. CSV files need newline="" when opening (per csv docs) to avoid extra blank lines on Windows.

Worked example.

import csv, json
from pathlib import Path
# CSV
rows = [{"name": "Asha", "age": 21}, {"name": "Binod", "age": 22}]
with Path("students.csv").open("w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["name", "age"])
    w.writeheader()
    w.writerows(rows)
with Path("students.csv").open(newline="", encoding="utf-8") as f:
    for r in csv.DictReader(f):
        print(r["name"], r["age"])
# JSON
data = {"course": "BCA254", "units": 9}
Path("data.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
loaded = json.loads(Path("data.json").read_text(encoding="utf-8"))
print(loaded["course"])                                  # BCA254

Output:

Asha 21
Binod 22
BCA254

Common mistake. Opening CSV files without newline="" adds blank rows on Windows; assuming JSON numbers stay as int after round-trip (they do, but floats may lose precision); json.load on malformed JSON raises json.JSONDecodeError.

Quick self-check. Q: What does JSON null become in Python? A: None. Q: Should CSV files be opened with newline=""? A: Yes.


5.3 Errors and exceptions

Explanation. An error is a problem in a program; an exception is the event raised when it happens at runtime. Python raises exceptions (raise) and programs can handle them. Built-in exceptions include SyntaxError (parse), NameError (undefined name), TypeError (wrong type), ValueError (right type, bad value), IndexError (bad sequence index), KeyError (missing dict key), FileNotFoundError, ZeroDivisionError, json.JSONDecodeError, RecursionError, EOFError, KeyboardInterrupt. All derive from BaseException → Exception. Use type(e).__name__ to inspect.

Worked example.

for bad in ["1/0", "int('x')", "[0][5]", "{'a':1}['b']"]:
    try:
        eval(bad)
    except Exception as e:
        print(bad, "→", type(e).__name__)
# 1/0 → ZeroDivisionError
# int('x') → ValueError
# [0][5] → IndexError
# {'a':1}['b'] → KeyError

Common mistake. Catching bare except: or except Exception too broadly hides bugs (including KeyboardInterrupt/SystemExit if bare). Catch only exceptions you can actually handle; let others propagate.

Quick self-check. Q: What exception is raised for division by zero? A: ZeroDivisionError. Q: What exception for a missing dictionary key? A: KeyError.


5.4 Handling exceptions

Explanation. Handle exceptions with try/except/else/finally. try runs code that may fail; except catches specific exceptions (list several or a tuple); except Exception as e binds the exception; else runs only if no exception; finally always runs (cleanup — close resources, release locks). raise throws an exception; raise ... from e chains causes. Custom exceptions subclass Exception. Handle only what you can handle; use specific except clauses ordered most-specific-first (subclasses before base classes). else is useful for code that should run only on success.

Worked example.

class NegativeError(Exception):
    pass

def sqrt(x):
    if x < 0:
        raise NegativeError("negative input")
    return x ** 0.5

for val in [9, -4, 16]:
    try:
        result = sqrt(val)
    except NegativeError as e:
        print(val, "error:", e)
    except TypeError as e:
        print(val, "type error:", e)
    else:
        print(val, "->", result)
    finally:
        print("  cleaned up for", val)
# 9 -> 3.0   cleaned up for 9
# -4 error: negative input   cleaned up for -4
# 16 -> 4.0   cleaned up for 16

Common mistake. Ordering except Exception before except ValueError makes the latter unreachable. Using finally to return a value masks exceptions. Not chaining exceptions loses the original cause.

Quick self-check. Q: When does else run? A: Only if no exception in try. Q: When does finally run? A: Always — success, exception, or return/break.


5.5 Seeing the ideas: records, safety switches and what really happens

Explanation. Conceptual summary: files are persistent records living outside the program; with is the safety switch guaranteeing cleanup. Exceptions separate normal logic from error handling — the "happy path" stays clear while except deals with failures. What really happens at runtime: the interpreter executes statements; when something goes wrong it raises an exception that unwinds the call stack looking for a matching except; finally runs as the stack unwinds; if nothing catches it, the program crashes with a traceback. Good design: validate early, fail fast, handle only locally recoverable errors, let the rest propagate.

Common mistake. Swallowing exceptions with bare except: pass hides failures and makes debugging nearly impossible — log or re-raise instead.

Quick self-check. Q: What does an uncaught exception do? A: Unwinds the call stack and crashes with a traceback. Q: What is with for files? A: Guaranteed cleanup (safety switch).


Unit 5 key terms

file, text file, mode, open(), with, context manager, read(), readline(), readlines(), write(), \n, pathlib.Path, encoding, utf-8, CSV, csv.reader, csv.writer, csv.DictReader, csv.DictWriter, newline="", JSON, json.dump, json.load, json.dumps, json.loads, dict/list/str/number mapping, error, exception, raise, try, except, else, finally, SyntaxError, NameError, TypeError, ValueError, IndexError, KeyError, FileNotFoundError, ZeroDivisionError, json.JSONDecodeError, custom exception, traceback, call stack unwind, fail fast.

Unit 5 summary

Unit 5 covers persistent data and error safety. Text files are opened with modes (r, w, a, x) and always via with so they close reliably; read lazily by iteration; pathlib.Path handles paths. CSV handles tables (csv.DictReader/Writer); JSON handles nested data (json.load/dump, mapping to dict/list/str/int/float/bool/None). Errors are problems; exceptions are runtime events (raise, try/except/else/finally). Common exceptions: ValueError, TypeError, IndexError, KeyError, FileNotFoundError, ZeroDivisionError, json.JSONDecodeError. Handle only what you can handle, with specific except clauses; finally always runs for cleanup; else runs only on success.

Unit 6: Object-Oriented Programming in Python (7 hrs)

6.1 Classes and objects

Explanation. A class is a blueprint (class Name:); an object (instance) is created by calling the class: obj = Name(). __init__(self, ...) initializes each new instance; self refers to the current instance (a convention, not a keyword). Attributes are self.name = value; methods are functions defined in the class taking self as first parameter. Classes bundle data and behaviour. type(obj) shows the class; isinstance(obj, Class) checks membership. Objects are mutable by default; attributes can be added anytime.

Worked example.

class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
    def greet(self):
        return f"Hi, I'm {self.name} (roll {self.roll})"

s1 = Student("Asha", 1)
s2 = Student("Binod", 2)
print(s1.name, s1.roll)                  # Asha 1
print(s1.greet())                        # Hi, I'm Asha (roll 1)
print(s2.greet())                        # Hi, I'm Binod (roll 2)
print(type(s1), isinstance(s1, Student)) # <class '__main__.Student'> True

Output:

Asha 1
Hi, I'm Asha (roll 1)
Hi, I'm Binod (roll 2)
<class '__main__.Student'> True

Common mistake. Calling Student.greet() without an instance passes no self → TypeError; forget self in method definition → TypeError at call (wrong argument count). Also self is positional-by-convention; you never pass it explicitly.

Quick self-check. Q: What is self? A: The current instance (first method parameter, convention). Q: How do you create an object from class Student? A: Student("Asha", 1).


6.2 Encapsulation

Explanation. Encapsulation bundles data and behaviour and controls access to internal state. Python has no true private members; by convention, names prefixed with _ (e.g., _balance) are "internal, don't touch from outside", and __ (double underscore) triggers name mangling (_ClassName__attr) to avoid subclass collisions — not real privacy. The Pythonic way is properties: @property exposes a getter, @name.setter a setter, letting you validate on assignment while keeping attribute syntax. Prefer attributes, add properties only when validation/lazy computation is needed.

Worked example.

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance          # conventional "internal"
    @property
    def balance(self):
        return self._balance
    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("balance cannot be negative")
        self._balance = value

a = Account("Asha", 100)
print(a.balance)                         # 100
a.balance = 150
print(a.balance)                         # 150
try:
    a.balance = -50                      # ValueError
except ValueError as e:
    print("ValueError:", e)
print(a._balance)                        # 150 (convention only, not enforced)

Output:

100
150
ValueError: balance cannot be negative
150

Common mistake. Believing _ or __ enforces privacy — it doesn't (name mangling is bypassable). Also mutating a mutable default or bypassing the setter by writing to _balance directly skips validation.

Quick self-check. Q: Does _balance enforce privacy? A: No — it's a convention only. Q: What does @property let you do? A: Expose attribute-like access with validation logic.


6.3 Inheritance and polymorphism

Explanation. Inheritance lets a subclass reuse and extend a parent class: class Child(Parent):. The child inherits attributes and methods and can override them; super().__init__(...) calls the parent initializer. Polymorphism lets different objects be treated uniformly through a shared interface — code calling a method works with any object that has that method ("duck typing": if it walks like a duck...). Abstract base classes (abc.ABC, @abstractmethod) force subclasses to implement a common interface. Inheritance models "is-a"; use it when the child truly is a kind of the parent.

Worked example.

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h
    def area(self):
        return self.w * self.h
class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14159 * self.r * self.r

shapes = [Rectangle(3, 4), Circle(2)]   # polymorphic list
for s in shapes:
    print(s.area())                     # 12, 12.56636

Output:

12
12.56636

Common mistake. Forgetting super().__init__() leaves parent attributes uninitialized. Using inheritance for "has-a" relationships instead of composition (e.g., a Car is not a kind of Engine; it has an Engine).

Quick self-check. Q: What does super().__init__() do? A: Calls the parent class initializer. Q: Is polymorphism about same method name, different behaviour per class? A: Yes.


6.4 Special methods and operator overloading

Explanation. Special ("dunder", double-underscore) methods let your classes integrate with Python syntax: __str__ (readable str()/print), __repr__ (unambiguous developer repr), __len__ (for len()), __getitem__/__setitem__ (for indexing obj[i]), __iter__/__next__ (for iteration), __add__, __sub__, __eq__, __lt__ (operators +, -, ==, <), __call__ (make object callable), __enter__/__exit__ (context manager). Operator overloading means redefining operators for your type via these methods. Always return sensible types (__add__ returns a new instance, not mutating self, usually).

Worked example.

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    def __str__(self):
        return f"({self.x}, {self.y})"
    def __len__(self):
        return 2
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1, repr(v1))                     # (1, 2) Vector(1, 2)
print(len(v1))                          # 2
v3 = v1 + v2
print(v3, v3 == Vector(4, 6))           # (4, 6) True

Output:

(1, 2) Vector(1, 2)
2
(4, 6) True

Common mistake. __eq__ without __hash__ makes objects unhashable (sets/dict keys break) because Python sets __hash__ = None when __eq__ is defined. Mutating self in __add__ surprises users — return a new object.

Quick self-check. Q: Which dunder makes print(obj) readable? A: __str__ (fallback __repr__). Q: Which dunder enables obj1 + obj2? A: __add__.


6.5 Dataclasses and composition

Explanation. @dataclass (from dataclasses) auto-generates __init__, __repr__, __eq__ for classes that mainly hold data; declare fields with type hints (name: str), optional defaults. Fields with defaults must come after fields without. dataclass(frozen=True) makes instances immutable. Composition means building a class from other objects as attributes ("has-a") rather than inheriting — e.g., a Student has an Address, a Course has Students. Composition is usually preferred over inheritance for flexibility; inheritance only for true "is-a".

Worked example.

from dataclasses import dataclass
@dataclass
class Address:
    street: str
    city: str
@dataclass
class Student:
    name: str
    roll: int
    address: Address                    # composition

addr = Address("Thapathali", "Kathmandu")
s = Student("Asha", 1, addr)
print(s)                                # Student(name='Asha', roll=1, address=Address(...))
print(s.address.city)                   # Kathmandu
s2 = Student("Asha", 1, addr)
print(s == s2)                          # True (auto __eq__)
try:
    s.name = "x"                        # allowed (not frozen)
except Exception as e:
    print(e)

Output:

Student(name='Asha', roll=1, address=Address(street='Thapathali', city='Kathmandu'))
Kathmandu
True

Common mistake. Dataclass fields with mutable defaults (items: list = []) are shared across instances — use field(default_factory=list). Forgetting that default fields must follow non-default fields raises TypeError at class definition.

Quick self-check. Q: What does @dataclass auto-generate? A: __init__, __repr__, __eq__ (and more). Q: What is composition? A: Building a class from other objects as attributes ("has-a").


6.6 Seeing the ideas: one mould, many objects

Explanation. Conceptual synthesis: a class is one mould; objects are many castings, each with its own state but shared behaviour. Encapsulation hides internals and exposes a clean surface. Inheritance specializes a mould; polymorphism lets one loop treat different moulds uniformly. Dunder methods let your moulds speak Python's own language (printing, length, operators). Dataclasses cut boilerplate for data moulds; composition assembles complex moulds from simple ones. Good OOP keeps classes small, single-purpose, and loosely coupled — easy to test and change.

Common mistake. Making classes too large or inheriting just to reuse code (implementation inheritance) rather than to model "is-a"; prefer composition and small, focused classes.

Quick self-check. Q: What is a class, metaphorically? A: One mould; objects are many castings. Q: Should inheritance model "has-a"? A: No — composition models "has-a"; inheritance models "is-a".


Unit 6 key terms

class, object, instance, __init__, self, attribute, method, type(), isinstance(), encapsulation, _name convention, __name name mangling, @property, setter, getter, inheritance, subclass, parent class, super(), override, polymorphism, duck typing, abc.ABC, @abstractmethod, "is-a", dunder, special method, __str__, __repr__, __len__, __getitem__, __add__, __eq__, __call__, operator overloading, @dataclass, type hints, frozen=True, field(default_factory=...), composition, "has-a", loose coupling.

Unit 6 summary

Unit 6 covers object-oriented programming. Classes are blueprints; objects are instances created by calling the class; __init__(self, ...) initializes state and self refers to the current instance. Encapsulation bundles data and behaviour — Python uses convention (_) and properties (@property) rather than hard privacy. Inheritance (class Child(Parent)) models "is-a" with super(); polymorphism lets different objects answer the same method; ABCs enforce interfaces. Dunder methods (__str__, __add__, __eq__, __len__, ...) integrate classes with Python syntax (operator overloading). @dataclass auto-generates boilerplate for data-holding classes. Composition ("has-a") builds complex objects from simple ones and is usually preferable to inheritance for code reuse.

Unit 7: Data Analysis and Visualisation: NumPy, Pandas, Matplotlib (7 hrs)

7.1 NumPy

Explanation. NumPy provides the ndarray — a homogeneous, multi-dimensional array for fast vectorised numerical work. Create arrays with np.array(...), np.zeros, np.ones, np.arange, np.linspace. Arrays have dtype, shape, ndim, size. Vectorised operations (a + b, a * 2) run element-wise without explicit loops; broadcasting lets arrays of different shapes operate together when compatible. Aggregations: sum, mean, min, max, std, argmax; linear algebra: np.dot, @, np.linalg.inv; slicing/indexing works like lists but multi-dimensional. NumPy is the foundation of Pandas and the scientific Python stack.

Worked example.

import numpy as np
a = np.array([1, 2, 3])            # 1-D array
b = np.array([4, 5, 6])
print(a + b)                       # [5 7 9]  vectorised
print(a * 2)                       # [2 4 6]
m = np.array([[1, 2], [3, 4]])     # 2-D
print(m.shape, m.ndim)             # (2, 2) 2
print(m[0, 1])                     # 2
print(m.mean(), m.sum())           # 2.5 10
print(m @ m)                       # matrix product [[7 10] [15 22]]
c = np.zeros((2, 3))
print(c)                           # [[0 0 0] [0 0 0]]

Output:

[5 7 9]
[2 4 6]
(2, 2) 2
2
2.5 10
[[7 10]
 [15 22]]
[[0. 0. 0.]
 [0. 0. 0.]]

Common mistake. NumPy arrays are homogeneous — mixing types forces upcasting (e.g. numbers and strings become all strings). np.array copies by default; slicing returns a view (shares memory), so modifying a slice modifies the original — use .copy() for an independent copy.

Quick self-check. Q: Does m[0:1] return a copy or a view of a NumPy array? A: A view (shares memory); use .copy() for independence. Q: What attribute gives an array's dimensions? A: .shape.


7.2 Pandas

Explanation. Pandas builds on NumPy and provides DataFrame (2-D labelled table, like a spreadsheet/SQL table) and Series (1-D labelled array). Create DataFrames from dicts of lists, CSV (pd.read_csv), or records. Columns are accessed by name (df["col"]), rows by label (df.loc) or position (df.iloc). Common operations: head(), info(), select dtypes, boolean filtering (df[df.age > 20]), dropna()/fillna() for missing data, groupby(...).agg(...) for grouping, merge/concat for combining, sort_values. Missing values are NaN (float). Pandas is the tool for cleaning and exploring tabular data.

Worked example.

import pandas as pd
df = pd.DataFrame({
    "name": ["Asha", "Binod", "Deepa"],
    "age": [21, 22, 20],
    "score": [85, 90, 78]
})
print(df[df.age > 20])            # Asha, Binod
print(df.groupby("age")["score"].mean())
# age
# 20    78.0
# 21    85.0
# 22    90.0
# Name: score, dtype: float64
print(df["score"].mean())         # 84.333...
df["passed"] = df["score"] >= 80
print(df[["name", "passed"]])

Output (excerpt):

    name  age  score
0  Asha   21     85
1 Binod   22     90
age
20    78.0
21    85.0
22    90.0
Name: score, dtype: float64
84.33333333333333
    name  passed
0  Asha     True
1 Binod    True
2 Deepa   False

Common mistake. df["col"] returns a Series; setting df["new"] = ... adds a column. Chained indexing (df[df.a>1]["b"] = x) can set values unpredictably (SettingWithCopy warning) — use df.loc[condition, "b"] = x instead. NaN != NaN, so use pd.isna() to detect missing values.

Quick self-check. Q: Is df.loc label-based or position-based? A: Label-based; df.iloc is position-based. Q: How to detect missing values? A: pd.isna() (not == NaN).


7.3 Matplotlib

Explanation. Matplotlib creates static charts. The pyplot interface (import matplotlib.pyplot as plt) is the common entry: plt.plot(x, y) for lines, plt.scatter(x, y) for scatter, plt.bar(categories, values) for bars, plt.hist(data) for histograms. Label with plt.xlabel, plt.ylabel, plt.title; plt.legend() labels series; plt.grid() adds grid; plt.show() displays (in scripts) and plt.savefig("fig.png") writes a file. Use plt.figure(figsize=(w,h)) for size and plt.clf()/plt.close() to clear figures between plots. Matplotlib works with lists, NumPy arrays, and Pandas Series/columns.

Worked example.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
plt.plot(x, y, marker="o", label="sales")
plt.xlabel("day")
plt.ylabel("amount")
plt.title("Daily sales")
plt.legend()
plt.grid(True)
plt.savefig("sales.png")   # writes file; use plt.show() in scripts/notebooks
plt.close()
print("saved sales.png")

Output:

saved sales.png

(a sales.png file is produced showing a line chart with markers, axis labels, title, legend, and grid)

Common mistake. Calling plt.show() before plt.savefig() can save a blank figure in some backends — save before showing, or use savefig only. Forgetting plt.close() in loops accumulates figures in memory. Not importing matplotlib.pyplot as plt.

Quick self-check. Q: Which function draws a line chart? A: plt.plot(x, y). Q: Should savefig come before or after show()? A: Before (or use only savefig).


7.4 Seeing the ideas: data made visible

Explanation. Conceptual summary: raw numbers are hard to grasp in bulk. NumPy turns lists into fast, vectorised arrays; Pandas turns CSV-style rows into queryable DataFrames; Matplotlib turns columns into charts the eye can read. The pipeline: load data → clean (handle missing, types) → transform (filter, group, aggregate) → visualise → communicate. Visualisation choices: line for trends over time, bar for categories, scatter for relationships, histogram for distributions. The goal is insight, not decoration — every chart should answer a question.

Common mistake. Picking a chart type that hides the data (e.g., pie charts for many categories, truncated y-axes that exaggerate differences) or plotting un-cleaned data (missing values, outliers) without noting it.

Quick self-check. Q: Which chart shows a relationship between two numeric variables? A: Scatter plot. Q: Does visualisation replace data cleaning? A: No — clean first, then visualise.


Unit 7 key terms

NumPy, ndarray, vectorised, broadcasting, dtype, shape, ndim, size, np.array, np.zeros, np.ones, np.arange, np.linspace, slicing, view, copy, np.dot, @, Pandas, DataFrame, Series, pd.read_csv, loc, iloc, boolean filtering, dropna, fillna, groupby, agg, merge, concat, NaN, pd.isna, Matplotlib, pyplot, plt.plot, plt.scatter, plt.bar, plt.hist, xlabel, ylabel, title, legend, grid, savefig, show, close, pipeline.

Unit 7 summary

Unit 7 covers data analysis and visualisation. NumPy's ndarray enables fast, vectorised numerical computing with broadcasting, aggregations, and linear algebra; slicing gives views (use .copy() for independence). Pandas' DataFrame handles labelled, heterogeneous tabular data — read CSV, filter, handle missing values (dropna/fillna, pd.isna), group and aggregate, merge. Matplotlib draws line/scatter/bar/histogram charts with labels, legends, and savefig/show. The analysis pipeline: load → clean → transform → visualise → communicate; choose chart type by the question asked.

Unit 8: Regular Expressions, Databases and Testing (5 hrs)

8.1 Regular expressions

Explanation. Regular expressions (regex) describe text patterns. Python's re module: re.compile(pattern) compiles; re.search(pattern, text) finds first match anywhere; re.match anchors at start; re.findall returns all matches as a list; re.sub(pattern, repl, text) replaces matches. Use raw strings r"..." so backslashes stay literal. Common symbols: . any char, \d digit, \D non-digit, \w word char, \s whitespace, ^ start, $ end, * zero or more, + one or more, ? zero or one, {m,n} range, [abc] character class, [^a-z] negated, (...) capturing group, (?P<name>...) named group, \1 backreference, | alternation. re.match only checks the beginning — use re.search to find anywhere.

Worked example.

import re
text = "Call 9801-234-5678 or email asha@example.com"
phone = re.search(r"\d{4}-\d{3}-\d{4}", text)
print(phone.group())                    # 9801-234-5678
emails = re.findall(r"\w+@\w+\.\w+", text)
print(emails)                           # ['asha@example.com']
cleaned = re.sub(r"\s+", " ", "a   b   c")
print(repr(cleaned))                    # 'a b c'
m = re.match(r"Hello", "Hello world")
print(bool(m))                          # True
print(bool(re.match(r"Hello", "x Hello")))  # False — match anchors at start

Output:

9801-234-5678
['asha@example.com']
'a b c'
True
False

Common mistake. Forgetting raw strings ("\d" becomes escape \d issues; use r"\d"); confusing re.match (start only) with re.search (anywhere); greedy quantifiers (.* matches as much as possible — use .*? for non-greedy).

Quick self-check. Q: Should regex patterns use raw strings? A: Yes — r"\d". Q: Does re.match find a pattern in the middle of a string? A: No — it anchors at the start; use re.search.


8.2 SQLite from Python

Explanation. SQLite is a zero-setup, file-backed SQL database; Python's sqlite3 module needs no server. Connect with sqlite3.connect("db.sqlite3"); use with con: for automatic transactions (commits on success, rolls back on exception). Create a cursor con.cursor(), run cur.execute(sql, params) with parameterised queries (? placeholders) — never f-strings with user input (SQL injection risk). Create tables (CREATE TABLE), insert (INSERT), query (SELECT), update (UPDATE), delete (DELETE). cur.fetchone()/cur.fetchall() read results. con.close() closes (or use with). Row factory sqlite3.Row gives dict-like access.

Worked example.

import sqlite3
con = sqlite3.connect(":memory:")   # in-memory database for the demo
con.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)")
with con:
    con.execute("INSERT INTO students (name, score) VALUES (?, ?)", ("Asha", 85))
    con.execute("INSERT INTO students (name, score) VALUES (?, ?)", ("Binod", 90))
cur = con.execute("SELECT name, score FROM students WHERE score > ?", (80,))
for row in cur:
    print(row)                        # ('Asha', 85) ('Binod', 90)
con.close()

Output:

('Asha', 85)
('Binod', 90)

Common mistake. Building SQL with f-strings (f"WHERE name = '{name}'") enables SQL injection — always use ? parameters. Forgetting with con:/con.commit() means inserts aren't persisted. Reusing a closed connection/cursor raises ProgrammingError.

Quick self-check. Q: Is f"WHERE id = {id}" safe for user input? A: No — SQL injection; use ? parameters. Q: What does with con: do in sqlite3? A: Commits on success, rolls back on exception.


8.3 Unit testing with unittest

Explanation. unittest is Python's built-in testing framework. Create a class subclassing unittest.TestCase; methods starting with test_ are tests. Assert methods: assertEqual(a, b), assertNotEqual, assertTrue(x), assertFalse(x), assertIsNone(x), assertIn(x, seq), assertRaises(Exception). setUp() runs before each test; tearDown() after. Run with python3 -m unittest (discovers test_*.py) or unittest.main(). Tests make change safe by catching regressions; each test should be independent and test one thing.

Worked example.

import unittest

def add(a, b):
    return a + b

def divide(a, b):
    if b == 0:
        raise ValueError("cannot divide by zero")
    return a / b

class TestMath(unittest.TestCase):
    def setUp(self):
        self.a, self.b = 2, 3
    def test_add(self):
        self.assertEqual(add(self.a, self.b), 5)
    def test_add_negative(self):
        self.assertEqual(add(-1, 1), 0)
    def test_divide_by_zero(self):
        self.assertRaises(ValueError, divide, 1, 0)

if __name__ == "__main__":
    unittest.main()
# Run: python3 test_math.py   -> . - Ran 3 tests, OK

Common mistake. Test methods not starting with test_ are skipped by discovery. Tests that share mutable state (global/db) break independence — use setUp()/fresh objects. Asserting exact floats (assertEqual(0.1+0.2, 0.3)) fails — use assertAlmostEqual.

Quick self-check. Q: What prefix must test methods have? A: test_. Q: How to assert an exception is raised? A: self.assertRaises(ValueError, func, args).


8.4 Virtual environments and pip

Explanation. Virtual environments isolate project dependencies so different projects can use different package versions without clashing. Create with python3 -m venv .venv; activate (source .venv/bin/activate on macOS/Linux, .venv\Scripts\activate on Windows); deactivate with deactivate. While activated, python/pip refer to the environment. pip install package installs; pip install -r requirements.txt installs from a list; pip freeze > requirements.txt records exact versions; pip list shows installed; pip uninstall package removes. Never commit the environment folder — commit requirements.txt instead and add .venv/ to .gitignore.

Worked example.

python3 -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txt
deactivate

Typical pip freeze output:

requests==2.31.0
certifi==2024.2.2
...

After deactivate, the system Python is used again and requests is unavailable unless installed globally.

Common mistake. Installing packages globally (sudo pip install) pollutes the system and can break OS tools — always use a virtual environment per project. Committing .venv/ to version control (huge, non-portable) — commit requirements.txt instead.

Quick self-check. Q: Command to create a venv? A: python3 -m venv .venv. Q: Should .venv/ be committed to Git? A: No — add to .gitignore; commit requirements.txt.


8.5 Seeing the ideas: patterns, records, checks and isolation

Explanation. Conceptual summary: regular expressions find/transform text patterns; SQLite stores structured records with SQL; unittest runs checks that protect code from regressions; virtual environments and pip isolate each project's dependencies. Together they represent the "professional" layer: pattern-based text processing, durable storage, automated verification, and reproducible environments. The thread is reliability — code that handles text safely, stores data durably, is proven by tests, and runs the same everywhere.

Common mistake. Treating these as optional extras rather than core engineering practice — projects without tests, parameterised queries, or isolated environments break silently and are hard to reproduce.

Quick self-check. Q: Which module handles parameterised SQLite queries? A: sqlite3 with ? placeholders. Q: Which tool isolates project dependencies? A: venv + pip.


Unit 8 key terms

regular expression, regex, re, raw string r"...", re.search, re.match, re.findall, re.sub, re.compile, ., \d, \w, \s, ^, $, *, +, ?, {m,n}, [], (), named group, greedy, non-greedy, SQLite, sqlite3, connect, cursor, execute, ? parameter, SQL injection, with con: transaction, fetchone, fetchall, CREATE TABLE, INSERT, SELECT, UPDATE, DELETE, unittest, TestCase, test_, assertEqual, assertRaises, setUp, tearDown, python3 -m unittest, virtual environment, venv, pip, requirements.txt, pip freeze, activate, deactivate, .gitignore.

Unit 8 summary

Unit 8 covers patterns, records, checks, and isolation. Regular expressions (re) match and transform text using raw strings and metacharacters (\d, ^, *, groups); prefer re.search over re.match for "anywhere" matching. SQLite (sqlite3) is a serverless file database — connect, create tables, and always use ? parameterised queries within with con: transactions to avoid SQL injection and guarantee commit/rollback. unittest (TestCase, test_ methods, assert methods, setUp) gives automated regression checks. venv and pip isolate project dependencies; record them in requirements.txt, never commit .venv/.

Unit 9: Putting It Together: Three Complete Programs (4 hrs)

9.1 Project 1: student-record manager

Explanation. A student-record manager combines earlier units: records (name, roll, marks) stored in memory or a file, with add/view/search/update/delete operations. Use a list of dicts or a small class per student; persist with JSON (json.dump/load) or a text file. Provide a menu loop (while True with input) and input validation. This project practices file I/O, exception handling, data structures, and a simple CLI. Keep functions small and single-purpose; separate data handling from presentation.

Worked example.

import json
from pathlib import Path

class RecordManager:
    def __init__(self, path="students.json"):
        self.path = Path(path)
        self.students = self._load()
    def _load(self):
        if self.path.exists():
            return json.loads(self.path.read_text(encoding="utf-8"))
        return []
    def save(self):
        self.path.write_text(json.dumps(self.students, indent=2), encoding="utf-8")
    def add(self, name, roll, marks):
        self.students.append({"name": name, "roll": roll, "marks": marks})
        self.save()
    def find(self, roll):
        return next((s for s in self.students if s["roll"] == roll), None)

rm = RecordManager()
rm.add("Asha", 1, 85)
rm.add("Binod", 2, 90)
print(rm.find(1))       # {'name': 'Asha', 'roll': 1, 'marks': 85}
print(rm.find(99))      # None
rm.save()

Output:

{'name': 'Asha', 'roll': 1, 'marks': 85}
None

(a students.json file is created)

Common mistake. Not validating input (non-integer roll/marks → ValueError); losing data by forgetting save() after mutations; next(...) raising StopIteration when no match — supply a default (None).

Quick self-check. Q: Which format persists the records in the example? A: JSON. Q: What does find return when no student matches? A: None (default supplied to next).


9.2 Project 2: text analyser

Explanation. A text analyser reads a text file and reports statistics: line count, word count, character count, and frequency of words. Uses strings (split, lower, strip), file reading (with open), dictionaries (word → count), and sorting (sorted(..., key=..., reverse=True)). Optionally uses regular expressions to extract words. Practices string processing, dictionaries, file I/O, and exceptions (FileNotFoundError). Output a summary report and top-N words.

Worked example.

from pathlib import Path
from collections import Counter
import re

def analyse(path):
    text = Path(path).read_text(encoding="utf-8")
    words = re.findall(r"\w+", text.lower())
    return {
        "chars": len(text),
        "words": len(words),
        "lines": text.count("\n") + 1,
        "top": Counter(words).most_common(3),
    }

report = analyse("sample.txt")  # file contains: "Hello world. Hello again."
print(report)

Output (for "Hello world. Hello again."):

{'chars': 25, 'words': 4, 'lines': 1, 'top': [('hello', 2), ('world', 1), ('again', 1)]}

Common mistake. Counting words with split(" ") (splits only single spaces, keeps punctuation attached) — use re.findall(r"\w+", ...) or .split(); forgetting FileNotFoundError handling for missing files; case-sensitivity ("Hello" vs "hello") — normalise with .lower().

Quick self-check. Q: Why lowercase text before counting words? A: So "Hello" and "hello" count as the same word. Q: Which function counts word frequencies? A: collections.Counter.


9.3 Project 3: a small bank in SQLite

Explanation. A small bank program persists accounts and transactions in SQLite. Schema: accounts(id, name, balance) and transactions(id, account_id, amount, type, timestamp). Operations: create account, deposit, withdraw, transfer (two updates in one transaction — atomicity via with con:). Uses parameterised queries (injection safety), exception handling (insufficient funds → ValueError), and sqlite3. This is the capstone combining OOP (Account class), files/database, exceptions, and transactions.

Worked example.

import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, balance INTEGER)")
con.execute("CREATE TABLE transactions (id INTEGER PRIMARY KEY, account_id INTEGER, amount INTEGER, type TEXT)")
with con:
    con.execute("INSERT INTO accounts (name, balance) VALUES (?, ?)", ("Asha", 1000))
    cur = con.execute("SELECT id FROM accounts WHERE name = ?", ("Asha",))
    aid = cur.fetchone()[0]
    con.execute("UPDATE accounts SET balance = balance - 200 WHERE id = ?", (aid,))
    con.execute("INSERT INTO transactions (account_id, amount, type) VALUES (?, ?, ?)", (aid, 200, "withdraw"))
cur = con.execute("SELECT name, balance FROM accounts")
print(cur.fetchall())             # [('Asha', 800)]
con.close()

Output:

[('Asha', 800)]

Common mistake. Doing a transfer as two separate execute calls without with con: — if the second fails, the first already committed (no atomicity). Not validating negative amounts or insufficient balance before UPDATE. Missing con.commit() outside with.

Quick self-check. Q: Why wrap deposit+withdraw in with con: for a transfer? A: Atomicity — both succeed or neither. Q: Which guard prevents SQL injection? A: ? parameterised queries.


9.4 Habits of a good Python programmer

Explanation. Good habits: write readable code (PEP 8 style, meaningful names, short functions); prefer explicit over implicit; use with for resources; handle specific exceptions, never bare except; validate input early and fail fast; write tests (unittest) for critical logic; use virtual environments and requirements.txt; use docstrings/comments sparingly but well; choose the right data structure; avoid premature optimisation; use == for value, is for identity (None); keep dependencies minimal; version-control code, not environments; learn the standard library before adding packages.

Worked example.

# Good: explicit, safe, documented
def compute_average(scores):
    """Return average of scores; raises ValueError if empty."""
    if not scores:
        raise ValueError("scores must not be empty")
    return sum(scores) / len(scores)

Common mistake. Writing clever one-liners that are hard to read; swallowing all exceptions; committing secrets or .venv/; ignoring return values of methods (e.g., calling list.sort() expecting a new list — it sorts in place and returns None).

Quick self-check. Q: Does list.sort() return the sorted list? A: No — it sorts in place and returns None; use sorted() for a new list. Q: Should you use bare except:? A: No — catch specific exceptions.


9.5 Seeing the ideas: from requirements to a working program

Explanation. Conceptual summary: a program starts from requirements (what it must do), is broken into small parts (functions, classes, modules), each part is written and tested, data storage is chosen (JSON/SQLite), errors are handled, and the whole is run through a CLI/menu. The three projects show the path: requirements → design → code → test → run → refine. Working software is built incrementally: get a small slice working, then extend. Keep pieces short, independent, and tested.

Common mistake. Trying to write the whole program at once before testing anything — build and test incrementally instead.

Quick self-check. Q: What is the recommended build order? A: Requirements → design → code → test → run → refine, incrementally. Q: Should pieces be short and independent? A: Yes — short, independent, tested pieces are easier to debug and reuse.


Unit 9 key terms

student-record manager, JSON, persistence, menu loop, while True, input validation, text analyser, word frequency, collections.Counter, re.findall, FileNotFoundError, small bank, SQLite, accounts, transactions, atomicity, transfer, with con:, parameterised queries, insufficient funds, OOP, Account class, habits, PEP 8, with, specific exceptions, fail fast, unittest, requirements.txt, .venv, requirements → design → code → test → run → refine, incremental, list.sort() vs sorted(), == vs is.

Unit 9 summary

Unit 9 integrates everything into three complete programs. Project 1 (student-record manager): records persisted in JSON, add/view/search via a menu loop, input validation. Project 2 (text analyser): reads a file, counts lines/words/chars, ranks word frequencies with Counter and regex. Project 3 (small bank in SQLite): accounts and transactions tables, deposit/withdraw/transfer with atomic with con: transactions and parameterised queries. Habits of a good programmer: readability (PEP 8), explicit safe code, with for resources, specific exceptions, tests, venv + requirements.txt, right data structures, incremental development (requirements → design → code → test → run → refine).

Practice questions and answers — Units 1–3

Q1. What is the output of print(0.1 + 0.2 == 0.3) and why?
A1. False — floats are IEEE-754 approximations; compare with abs(a-b) < 1e-9.

Q2. What does type(True) return, and is bool a subclass of int?
A2. <class 'bool'>; yes, bool subclasses int (True == 1).

Q3. What error does print(y) raise if y was never assigned?
A3. NameError: name 'y' is not defined.

Q4. What are range(3) values?
A4. 0, 1, 2 — stop is exclusive.

Q5. Does loop else run after break?
A5. No — only when the loop finishes without break.

Q6. What does "abc"[::-1] return?
A6. "cba".

Q7. Does b = a copy a list a?
A7. No — both names bind the same list; use a.copy() or list(a).

Q8. Can s[0] index a set?
A8. No — raises TypeError; sets are unordered and not subscriptable.

Q9. What does d.get("k", 0) return if key "k" is missing?
A9. 0.

Q10. Which container is best for fast "is x present?" tests?
A10. set — O(1) average membership.


Practice questions and answers — Units 4–6

Q1. What does a function with no return return?
A1. None.

Q2. What does LEGB stand for?
A2. Local, Enclosing, Global, Built-in.

Q3. What error results from recursion without a base case?
A3. RecursionError: maximum recursion depth exceeded.

Q4. Do map/filter return lists in Python 3?
A4. No — iterators; wrap with list().

Q5. Which mode opens a file for writing and truncates it?
A5. "w".

Q6. What exception is raised for a missing dictionary key?
A6. KeyError.

Q7. When does finally run?
A7. Always — success, exception, return, or break.

Q8. What is self?
A8. The current instance (first method parameter, by convention).

Q9. Does @dataclass auto-generate __init__?
A9. Yes — plus __repr__ and __eq__.

Q10. Does inheritance model "has-a"?
A10. No — composition models "has-a"; inheritance models "is-a".


Practice questions and answers — Units 7–9

Q1. Does slicing a NumPy array return a copy or a view?
A1. A view (shares memory); use .copy() for independence.

Q2. Is df.loc label-based or position-based?
A2. Label-based (df.iloc is position-based).

Q3. Which Matplotlib function draws a line chart?
A3. plt.plot(x, y).

Q4. Should savefig be called before or after show()?
A4. Before (or use savefig only).

Q5. Which re function finds a pattern anywhere in a string?
A5. re.search (re.match anchors at the start).

Q6. Is f-string SQL safe for user input?
A6. No — SQL injection; use ? parameterised queries.

Q7. What does with con: do in sqlite3?
A7. Commits on success, rolls back on exception.

Q8. What prefix must unittest methods have?
A8. test_.

Q9. Command to create a virtual environment?
A9. python3 -m venv .venv.

Q10. Does list.sort() return a new sorted list?
A10. No — sorts in place and returns None; use sorted().