Python, by example
Python by example - annotated code snippets covering the language from first principles to production.
20 lessons · Updated 2026-05-08
- 01Hello WorldThe smallest runnable Python program - printing a message and understanding the script guard pattern.
- 02ValuesPython's built-in scalar types: int, float, str, bool, None, and bytes - with identity versus equality.
- 03VariablesVariables in Python are name bindings. Understand multiple assignment, LEGB scope, and the UnboundLocalError trap.
- 04NumbersPython's three numeric types: int (arbitrary precision), float (IEEE 754), and complex - plus Decimal for exact arithmetic.
- 05StringsPython str is an immutable sequence of Unicode code points, not bytes. Encoding, f-strings, and grapheme-aware slicing.
- 06Booleans and TruthinessPython bool - True and False, truthy and falsy values, short-circuit operators, and when to use is vs ==.
- 07ConditionalsPython branching with if/elif/else, conditional expressions, and structural pattern matching with match/case (3.10+).
- 08LoopsPython for and while loops, enumerate and zip for cleaner iteration, break and continue, and the for/else clause.
- 09ListsPython list basics: append, extend, slicing, shallow copies, and the shared-reference trap with [[]] * n.
- 10TuplesPython tuple basics: packing and unpacking, the one-tuple comma, *rest unpacking, and typing.NamedTuple for named fields.
- 11DictsPython dict basics: safe access with .get(), defaultdict bucketing, merging with |, and the setdefault idiom.
- 12SetsPython set basics: literals, the empty-set {} trap, set algebra, deduplication, and frozenset for immutable membership.
- 13ComprehensionsList, dict, set, and generator comprehensions: concise collection building, generator laziness, and the walrus operator for filter-and-bind.
- 14FunctionsPython function signatures: keyword-only and positional-only args, the mutable-default footgun, and returning multiple values cleanly.
- 15Closures and DecoratorsClosures capture enclosing variables; decorators wrap functions. Covers the late-binding-in-loops bug and correct use of @functools.wraps.
- 16Generators and IteratorsGenerators produce values lazily with yield, iterate once, and pair with itertools for constant-memory pipelines.
- 17Classes and DataclassesPython classes group state and behaviour; dataclasses generate the boilerplate; frozen=True and slots=True give you hashable, memory-efficient value objects.
- 18Exceptionstry/except/else/finally, raise...from for chaining, and ExceptionGroup for handling multiple concurrent failures in Python 3.11+.
- 19Context ManagersContext managers pair setup and teardown in a with block. Use pathlib + with for files, contextlib.contextmanager for one-offs.
- 20Async and awaitasync/await runs concurrent I/O on a single thread via asyncio. TaskGroup (3.11+) gives fail-fast fan-out with structured cancellation.
Enjoyed this? Get more essays on software craft delivered to your inbox.
Subscribe free