01Module · Goodrich Ch. 1

Week 1 — Python Primer & Computational Foundations

Objects, control flow, functions, exceptions, iterators/generators, comprehensions, and modules — the Python substrate for the rest of the course.

Python Primer & Computational Foundations

Python's object model, expressions, control flow, functions, I/O, exceptions, iterators/generators, comprehensions, scopes, and modules.

Theory

Python uses a reference model: variables are names bound to objects on the heap. Assignment never copies — it rebinds.

Every value is an object with a type and an identity. Mutable (list, dict, set) vs immutable (int, str, tuple) semantics drive most subtle bugs.

Iterators implement __iter__ and __next__; generators are iterators built with the yield keyword, evaluated lazily.

Exception handling separates the happy path from error recovery and supports cleanup via try/except/finally.

Key points

  • is checks identity; == checks equality — they are not the same.
  • Default mutable arguments are evaluated once and shared across calls — avoid def f(x=[]).
  • Generators are O(1) memory; list comprehensions materialize all elements at once.
  • Modules are cached in sys.modules after first import.

Code examples

Generator vs list comprehension
Generator vs list comprehension
# Materializes all squares at once — O(n) memory
squares_list = [x * x for x in range(10_000_000)]

# Yields squares lazily — O(1) memory
squares_gen = (x * x for x in range(10_000_000))

total = 0
for s in squares_gen:
    total += s
Exception handling with cleanup
Exception handling with cleanup
def read_first_line(path):
    f = open(path, "r")
    try:
        return f.readline()
    except OSError as e:
        print(f"I/O failure: {e}")
        return None
    finally:
        f.close()  # always runs