Python Story

Chapter #2 – Python Survey

types, control flow, functions, classes, modules, exceptions

2.0 Survey Prologue

This chapter provides a brief survey of major Python language features. Each topic is explored in much more detail in later chapters. The goal here is to build a mental map so that later chapters feel like familiar territory.

2.1 Types

Python's built-in types cover the most common needs: Numeric: int (arbitrary precision), float (64-bit IEEE 754), complex, bool (subclass of int). Sequences: str (immutable), bytes (immutable), list (mutable), tuple (immutable). Mappings and sets: dict, set, frozenset. None: the singleton None represents the absence of a value. Type inference and hints: variables need no declaration. Optional type hints annotate intent: x: int = 42.

2.2 Control Flow

Standard statements: if / elif / else, for, while, break, continue, pass, return, raise. Python 3.10+ adds structural pattern matching with match / case: match command.split(): case ["quit"]: quit() case ["go", direction]: move(direction) case ["pick", "up", item]: pick_up(item) case _: print("unknown command") for iterates over any iterable. The optional else clause on a for or while loop runs only when no break occurred.

2.3 Functions

Functions are first-class objects defined with def. They support positional, keyword, default, variadic (*args), and keyword-variadic (**kwargs) parameters. def greet(name: str, *, loud: bool = False) -> str: msg = f"Hello, {name}!" return msg.upper() if loud else msg print(greet("Alice")) # Hello, Alice! print(greet("Bob", loud=True)) # HELLO, BOB! Lambda expressions create small anonymous functions: square = lambda x: x * x

2.4 Classes

A class bundles data (attributes) and behavior (methods). __init__ initializes instances; self is the conventional name for the instance reference passed as the first parameter. class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def distance(self) -> float: return (self.x**2 + self.y**2) ** 0.5 def __repr__(self) -> str: return f"Point({self.x}, {self.y})" p = Point(3, 4) print(p.distance()) # 5.0

2.5 Comprehensions and Generators

List comprehensions build lists concisely: squares = [x * x for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64] Dict and set comprehensions use the same syntax with {}: {k: v for k, v in pairs}. Generator expressions use () and produce values lazily: total = sum(x*x for x in range(1000000)) — no intermediate list. Generator functions use yield to emit values one at a time, enabling memory-efficient pipelines.

2.6 Decorators

A decorator is a callable that wraps another callable to extend its behavior. The @ syntax is syntactic sugar for function composition: import functools def log_call(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"calling {func.__name__}") return func(*args, **kwargs) return wrapper @log_call def add(a, b): return a + b add(2, 3) # prints "calling add", returns 5 The standard library provides ready-made decorators: @staticmethod, @classmethod, @property, @functools.lru_cache, @dataclasses.dataclass.

2.7 Modules and Packages

Any .py file is a module. A directory containing an __init__.py (or implicitly in Python 3.3+) is a package. import math # import a module from pathlib import Path # import a specific name import numpy as np # import with alias Third-party packages are installed with pip install <package> and isolated per project using virtual environments (python -m venv .venv).

2.8 Exception Handling

Python uses try / except / else / finally for structured error handling. Exceptions are objects that inherit from BaseException. try: result = int(input("number: ")) except ValueError as e: print(f"not a number: {e}") except (TypeError, OverflowError): print("conversion problem") else: print(f"got {result}") # runs only if no exception finally: print("done") # always runs Raise custom exceptions by subclassing Exception: class AppError(Exception): pass

2.9 Epilogue

This survey covered the shape of the Python language. Subsequent chapters look at each area in depth with code examples and design guidance.

2.10 References

Python Tutorial — python.org
Compound statements — python.org
PEP 636 — Structural Pattern Matching Tutorial