thecodex.expert · The Codex Family of Knowledge

🐍 Python · Cradle to Mastery

The Complete Python Course

One structured path from "I've never written code" to professional Python. 89 lessons across 7 stages — every lesson links to a dedicated reference page with 3 reading levels and official sources.

7 Stages· 89 Lessons· 14 Projects· Approximately 55 hours total reading time· Target level: Absolute beginner through Professional
Start from the beginning → I already know the basics

How to use this course

1
Follow the stages in orderEach stage builds on the previous. Don't skip — the sequence is deliberate.
2
Click the reading linkEach lesson links to a full reference page. That page IS the lesson — with code, 3 reading levels, and official sources.
3
Every page has 3 depthsBeginner, Intermediate, Expert. Each lesson card tells you which tabs to read and in what order.
4
The course banner guides youEvery reference page shows your lesson number, which stage you're in, what to read, and prev/next lesson links.
Casual: 2–3 lessons per week — 4–6 months
Structured: 1 stage per week — 7 weeks
Intensive: 1–2 lessons per day — 4–5 weeks

Learning Outcomes

Upon completion of this course, students will be able to:

  • Write Python programs from scratch — variables, functions, classes, error handling, file I/O, and modules
  • Use Python's standard library confidently across 11 modules including os, json, re, datetime, asyncio, and logging
  • Write clean, professional Python with type annotations, comprehensions, and proper project structure
  • Choose the correct concurrency model for a given task — threading, multiprocessing, or asyncio
  • Write automated test suites using pytest and mock external dependencies with unittest.mock
  • Understand how programming concepts (variables, scope, OOP, concurrency) work across languages, not just in Python
  • Build 14 complete projects ranging from a number guessing game to a working web server
Source standards: All reading materials in this course link to official Python documentation (docs.python.org), Python Enhancement Proposals (PEPs), or verified primary sources. Every reference page cites its primary source explicitly. There are no paywalls, no affiliate links, and no advertising. This course is free to use for any purpose.

Course Stages — Recommended sequential study

Stage 0 Before You Start 2 lessons · ~1 hour · No experience needed

Understand what Python is and get your environment ready before writing a single line of code. These two lessons take about an hour and make everything that follows significantly easier.

LESSON 1

What is Python?

Language philosophy, real-world uses, and how the interpreter works

Before writing any code, understand what you are actually working with. Python is used at Google, Netflix, NASA, and by leading AI researchers — yet it was deliberately designed to read like English. This lesson explains what Python is, what problems it solves, and how an interpreted language works.

📚 🟩 Read the Beginner tab only.
Key focus: Focus on: what Python is used for, and why it reads like English compared to other languages.
⏱ 30 min
Required Reading
What is Python? — The Codex

What programming languages are, why Python exists, real-world uses, and a side-by-side comparison with Java and C++.

LESSON 2

Setting Up Python

Installation, code editors, and running your first program

Having Python installed and a proper editor ready is the difference between a frustrating first week and a smooth one. This lesson walks through installation on Windows, macOS, and Linux; setting up VS Code; and running your first program.

📚 🟩 Read the Beginner tab only.
Key focus: Focus on: actually running the installation steps, not just reading them. By the end, run hello.py yourself.
⏱ 30 min
Required Reading
Setting Up Python — The Codex

Step-by-step installation for all platforms, VS Code setup, writing and running hello.py, the interactive shell, and the three most common setup mistakes.

Stage 1 Language Fundamentals 5 lessons · 3 reading levels each · ~8 hours total

The core Python language. Each page has three reading levels — Beginner, Intermediate, and Expert. In Stage 1, read Beginner first, then return to Intermediate when you feel ready. The Expert tab explains the why behind the design — read it when you want to go deeper, not on your first pass.

LESSON 3

Variables & Data Types

Python's 12 built-in types, mutability, and the object model

Every program manipulates data. Python has twelve built-in types — integers, floats, strings, booleans, lists, tuples, sets, dicts, and more. The Beginner tab covers the type table and basic assignment. The Intermediate tab covers mutability in depth — understanding mutable vs immutable prevents the most common category of Python bugs. The Expert tab covers Python's object model — why everything in Python is an object.

📚 🟩 Beginner tab first. Return for 🔵 Intermediate when comfortable.
Key focus: Focus on: the mutability column in the type table. This is the single most important concept in this lesson — mutable objects shared between variables produce the bugs that trip up every beginner.
⏱ Beginner: 40 min · Intermediate: 40 min · Expert: 20 min
Required Reading
Variables & Types — The Codex

Python's 12 built-in types, the mutability table (8 sections across 3 levels), type conversion, assignment vs equality, the is vs == distinction, names and objects, and Python's data model.

LESSON 4

f-strings & String Formatting

Formatted string literals, format spec, debugging with =

f-strings (formatted string literals, PEP 498) are the modern way to build strings in Python. The Beginner tab covers basic interpolation and expressions inside braces. The Intermediate tab covers the format specification mini-language — alignment, padding, number formatting, and the = debugging syntax. The Expert tab covers conversion flags and performance versus older formatting methods.

📚 🟩 Beginner first — f-strings are used in almost every Python program.
Key focus: Focus on: the format spec mini-language for numbers — f'{price:.2f}' and f'{value:,}' appear constantly in real code.
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 15 min
Required Reading
f-strings — The Codex

Formatted string literals (PEP 498), expressions inside braces, the format specification mini-language, alignment and padding, number and date formatting, the = debugging syntax (3.8+), and conversion flags.

LESSON 5

String Methods

case, strip, split, join, find, replace, validation

Python strings have 40+ built-in methods. The Beginner tab covers the everyday ones — case conversion, whitespace stripping, searching, and replacing. The Intermediate tab covers split/join (the backbone of parsing) and validation methods. The Expert tab covers immutability, interning, and why join beats += in loops.

📚 🟩 Beginner, then 🔵 Intermediate (split/join).
Key focus: Focus on: split and join — the two operations at the heart of nearly all text processing.
⏱ Beginner: 30 min · Intermediate: 30 min · Expert: 20 min
Required Reading
String Methods — The Codex

Case conversion, whitespace stripping, find/index/replace, split and join, validation methods (isdigit/isalpha), alignment (zfill/ljust/center), removeprefix/removesuffix, and string immutability.

LESSON 6

Control Flow & Loops

if/elif/else, for, while, match, iterators, comprehension forms

This is where programs start to feel alive. The Beginner tab covers if/elif/else and basic for/while loops — enough to write real programs. The Intermediate tab covers the iteration protocol (how for loops actually work), the match statement (Python 3.10+), and loop control (break/continue/else). The Expert tab explains how Python evaluates boolean expressions and the formal semantics of pattern matching.

📚 🟩 Beginner tab first. The Intermediate tab is important — come back to it.
Key focus: Focus on: what 'truthy' and 'falsy' mean. Almost every if condition in Python relies on this and it behaves differently from what beginners expect.
⏱ Beginner: 40 min · Intermediate: 40 min · Expert: 20 min
Required Reading
Control Flow & Loops — The Codex

if/elif/else, for loops over lists and ranges, while with conditions, break/continue/else on loops, range(), iterators and the iteration protocol, structural pattern matching (match/case, Python 3.10+), and boolean expression evaluation.

LESSON 7

match / case

Structural pattern matching, destructuring, class patterns

The match statement (Python 3.10+) is far more powerful than a switch. The Beginner tab covers literal matching, the _ wildcard, and destructuring sequences. The Intermediate tab covers class patterns, guards, and mapping patterns. The Expert tab covers PEP 634 semantics and __match_args__.

📚 🟩 Beginner, then 🔵 Intermediate. Requires Python 3.10+.
Key focus: Focus on: destructuring — matching the shape of data, not just a single value. That is what makes match more than a switch.
⏱ Beginner: 40 min · Intermediate: 35 min · Expert: 20 min
Required Reading
match/case — The Codex

Literal patterns, the _ wildcard, | OR patterns, sequence destructuring, capture patterns, class patterns with attributes, guards, mapping patterns for dicts, and __match_args__ for positional matching.

LESSON 8

Comprehensions

List, dict, set, and generator expressions — Python at its most elegant

Comprehensions are the most distinctively Pythonic feature. Once you learn them, you'll use them constantly. The Beginner tab shows list comprehensions with and without filters, and dict/set comprehensions. The Intermediate tab covers generator expressions (memory-efficient, lazy) and nested comprehensions. The Expert tab explains comprehension scoping, the walrus operator (:=), and the LIST_APPEND bytecode optimisation.

📚 🟩 Beginner tab. 🔵 Intermediate is quick and worth reading in the same session.
Key focus: Focus on: the difference between [x for x in ...] (list — builds immediately) and (x for x in ...) (generator — lazy). This is the key decision you make every time you write a comprehension.
⏱ Beginner: 35 min · Intermediate: 35 min · Expert: 20 min
Required Reading
Comprehensions — The Codex

List comprehensions with filters, dict and set comprehensions, generator expressions vs list comprehensions (memory model), nested for clauses, walrus operator (:=, PEP 572), and the LIST_APPEND bytecode optimisation.

LESSON 9

Iterators & Iterables

iterable vs iterator, the protocol, lazy evaluation

Every for loop is built on iterators. The Beginner tab covers the iterable-vs-iterator distinction and how iter()/next() power loops. The Intermediate tab covers the protocol and custom iterators. The Expert tab covers lazy evaluation, infinite iterators, and the two-argument iter().

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: iterables can be looped many times; iterators are single-use. This distinction explains most iteration surprises.
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 20 min
Required Reading
Iterators & Iterables — The Codex

Iterable vs iterator, iter() and next(), the iterator protocol (__iter__/__next__), StopIteration, custom iterators, generators as iterators, lazy evaluation, itertools, and the two-argument iter(callable, sentinel).

LESSON 10

Functions & Scope

def, *args/**kwargs, LEGB, closures, decorators, generators

A function lets you name a block of code and call it whenever you need it. Without functions, every program is a long list of instructions you can never reuse. The Beginner tab covers defining functions, parameters, defaults, and return. The Intermediate tab covers *args/**kwargs, LEGB scope, and lambda. The Expert tab covers closures, decorators, and generator functions with yield — advanced Python that professionals use daily.

📚 🟩 Beginner tab, then 🔵 Intermediate. The 🔴 Expert tab (closures + decorators) is very rewarding — save it for a second session.
Key focus: Focus on: the LEGB rule. Understanding Local → Enclosing → Global → Built-in scope resolution prevents 90% of NameError bugs and makes closures and decorators click immediately.
⏱ Beginner: 45 min · Intermediate: 45 min · Expert: 30 min
Required Reading
Functions & Scope — The Codex

Defining and calling functions, positional and keyword parameters, default values, *args and **kwargs, LEGB scope rule, lambda functions, closures (captured variables), decorators (@syntax and manual), and generator functions with yield.

LESSON 11

Lambda Functions

anonymous functions, sort keys, map/filter

A lambda is a small anonymous function in one expression. The Beginner tab covers lambda vs def. The Intermediate tab covers the main use (sort keys) plus map/filter/reduce. The Expert tab covers the function object and the late-binding trap.

📚 🟩 Beginner, then 🔵 Intermediate (sort keys).
Key focus: Focus on: using lambda as a key= for sorted/min/max. That is the ideal use; prefer comprehensions over map/filter+lambda.
⏱ Beginner: 20 min · Intermediate: 20 min · Expert: 20 min
Required Reading
Lambda Functions — The Codex

lambda vs def, single-expression bodies, sort keys for sorted/min/max, map/filter/reduce, comprehensions as alternatives, the late-binding closure trap, and lambda __name__.

LESSON 12

Closures

Captured variables, cell objects, nonlocal, factory functions

A closure is a function that remembers variables from its enclosing scope even after that scope has finished. The Beginner tab covers what closures are and the nonlocal keyword. The Intermediate tab covers inspecting closures and real-world patterns like memoisation. The Expert tab covers CPython cell objects and bytecode. Closures are the foundation of decorators — learn them first.

📚 🟩 Beginner first. Closures unlock decorators, so do not skip.
Key focus: Focus on: why nonlocal is required to reassign a captured variable, and the classic loop closure bug.
⏱ Beginner: 30 min · Intermediate: 25 min · Expert: 20 min
Required Reading
Closures — The Codex

Closure conditions, captured free variables, the nonlocal keyword, __closure__ and cell objects, memoisation, and CPython MAKE_CELL/STORE_DEREF/LOAD_DEREF bytecode.

LESSON 13

Decorators

@syntax, functools.wraps, stacking, class decorators

A decorator wraps a function to extend it without changing its source. The Beginner tab establishes that @decorator is exactly func = decorator(func). The Intermediate tab covers decorator factories (decorators with arguments), stacking, and class decorators. The Expert tab covers the descriptor protocol behind @property. Decorators appear everywhere — Flask, pytest, dataclasses.

📚 🟩 Beginner, then 🔵 Intermediate. Always use @functools.wraps.
Key focus: Focus on: the equivalence @decorator == func = decorator(func). Once automatic, every decorator becomes readable.
⏱ Beginner: 35 min · Intermediate: 35 min · Expert: 25 min
Required Reading
Decorators — The Codex

The @syntax equivalence, functools.wraps, timing and retry decorators, decorator factories with arguments, stacking, class decorators, @dataclass internals, and the descriptor protocol behind @property.

LESSON 14

Generators

yield, lazy evaluation, pipelines, yield from, send()

A generator produces values lazily, one at a time, using yield. The Beginner tab covers yield and the dramatic memory savings versus lists. The Intermediate tab covers generator pipelines and yield from. The Expert tab covers generator internals and the send() protocol that powers coroutines. Essential for processing large data efficiently.

📚 🟩 Beginner, then 🔵 Intermediate (pipelines).
Key focus: Focus on: the memory comparison — a list comprehension builds everything in memory; a generator expression uses constant memory.
⏱ Beginner: 35 min · Intermediate: 30 min · Expert: 25 min
Required Reading
Generators — The Codex

yield vs return, lazy evaluation, memory efficiency, infinite generators, generator pipelines, yield from delegation, send() for coroutines, and CPython gi_frame internals.

LESSON 15

Context Managers

with statement, __enter__/__exit__, @contextmanager, ExitStack

A context manager guarantees setup and cleanup using the with statement, even when exceptions occur. The Beginner tab covers the with statement and why it is the only safe way to manage resources. The Intermediate tab covers implementing __enter__/__exit__ and the @contextmanager decorator. The Expert tab covers ExitStack and async context managers.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: always using with for files, locks, and connections — and why returning True from __exit__ suppresses exceptions.
⏱ Beginner: 30 min · Intermediate: 35 min · Expert: 20 min
Required Reading
Context Managers — The Codex

The with statement, __enter__/__exit__ protocol, @contextlib.contextmanager, contextlib.suppress, ExitStack for dynamic management, and async with.

LESSON 16

Object-Oriented Python

Classes, inheritance, dataclasses, dunder methods, metaclasses

Object-oriented programming is how most serious Python programs are structured. The Beginner tab covers classes, __init__, instance vs class attributes, and basic inheritance. The Intermediate tab covers dunder methods (__str__, __len__, __eq__), properties, and dataclasses (Python 3.7+'s elegant shorthand). The Expert tab covers multiple inheritance, the Method Resolution Order (MRO), the descriptor protocol, and metaclasses.

📚 🟩 Beginner, then 🔵 Intermediate. Dunder methods are key — learn them. 🔴 Expert (metaclasses) can wait.
Key focus: Focus on: dataclasses. They are the modern, clean way to write data-holding classes in Python and you will encounter them in almost every professional codebase.
⏱ Beginner: 50 min · Intermediate: 50 min · Expert: 30 min
Required Reading
Object-Oriented Python — The Codex

Defining classes with __init__, instance vs class attributes, inheritance and method resolution, special methods (__str__, __repr__, __len__, __eq__, __lt__), @property, dataclasses (@dataclass, field()), multiple inheritance and MRO (C3 linearisation), the descriptor protocol, and metaclasses.

LESSON 17

Dataclasses

@dataclass, fields, defaults, frozen, field(), __post_init__

The @dataclass decorator auto-generates __init__, __repr__, and __eq__ from annotated fields. The Beginner tab covers basic dataclasses and defaults. The Intermediate tab covers frozen/order/slots, field(default_factory), and __post_init__. The Expert tab covers the code-generation mechanism and introspection API.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: field(default_factory=list) for mutable defaults — never use list/dict directly as a default.
⏱ Beginner: 30 min · Intermediate: 30 min · Expert: 20 min
Required Reading
Dataclasses — The Codex

@dataclass decorator, annotated fields, default values, frozen for immutability, order for comparisons, slots for memory, field(default_factory) for mutable defaults, __post_init__ for validation, and the asdict/fields introspection API.

LESSON 18

Enums

Enum, IntEnum, StrEnum, Flag, auto(), @unique

An enum is a set of named constants. The Beginner tab covers defining and accessing enums and why they replace magic values. The Intermediate tab covers IntEnum, StrEnum, Flag, auto(), methods, and @unique. The Expert tab covers EnumMeta, the functional API, and the _missing_ hook.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: the difference between plain Enum (members not equal to values) and IntEnum (members equal their int value).
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 20 min
Required Reading
Enums — The Codex

Defining enums, accessing members by attribute/value/name, member.name and .value, iteration, IntEnum and StrEnum, Flag with bitwise operators, auto(), enum methods, aliases, @unique, and the _missing_ hook.

LESSON 19

Abstract Base Classes

@abstractmethod, interfaces, collections.abc

An ABC defines an interface subclasses must implement. The Beginner tab covers @abstractmethod and instantiation errors. The Intermediate tab covers abstract properties and register(). The Expert tab covers ABCMeta and collections.abc mixins.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: the error fires at instantiation, not definition — you can never create an incomplete object.
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 20 min
Required Reading
Abstract Base Classes — The Codex

ABC and @abstractmethod, instantiation enforcement, abstract properties, concrete+abstract mixing, register() for virtual subclasses, __subclasshook__, ABCMeta, and the collections.abc container ABCs with free mixin methods.

LESSON 20

The Data Model

dunder methods, __repr__, container protocol, operators

The data model is the set of dunder methods Python calls for built-in syntax. The Beginner tab covers __init__/__repr__/__str__/__eq__. The Intermediate tab covers the container protocol and operator overloading. The Expert tab covers reflected operators, __new__, and attribute hooks.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: len(x) calls x.__len__(), a+b calls a.__add__(b). Implement dunders and your objects work with built-in syntax.
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 20 min
Required Reading
Python Data Model — The Codex

Dunder methods as hooks, __repr__ vs __str__, __eq__ and __hash__, the container protocol (__len__/__getitem__/__contains__), operator overloading, __call__, reflected operators, __new__ vs __init__, and attribute hooks.

Stage 2 Professional Python 6 lessons · 3 reading levels each · ~12 hours total

The skills that separate functional Python from professional Python. Read Beginner and Intermediate tabs in Stage 2 — they are both essential. The Expert tabs explain internals and edge cases; save them for a second pass or when debugging a specific issue.

LESSON 21

Error Handling

try/except/else/finally, custom exceptions, context managers, exception groups

Real programs encounter unexpected situations. The Beginner tab covers try/except and the exception hierarchy — the 10 most common built-in exceptions and when each appears. The Intermediate tab covers context managers (the with statement) and writing custom exception classes. The Expert tab covers CPython's zero-cost exception model, PEP 654 exception groups (Python 3.11+), and PEP 3151's OS error hierarchy.

📚 🟩 Beginner, then 🔵 Intermediate. Context managers are essential for professional code.
Key focus: Focus on: why 'except Exception:' is always preferable to bare 'except:'. Catching everything silences programming errors — the single most dangerous habit in Python error handling.
⏱ Beginner: 40 min · Intermediate: 40 min · Expert: 25 min
Required Reading
Error Handling — The Codex

Python's exception hierarchy (BaseException vs Exception), try/except/else/finally, catching multiple exceptions, as e binding, re-raising, exception chaining (raise X from Y), custom exception classes, context managers (__enter__/__exit__), contextlib.contextmanager, suppress(), and exception groups (except*, Python 3.11+).

LESSON 22

Exception Hierarchy

BaseException tree, catching by level, custom exceptions

Every exception is a class in one tree. The Beginner tab covers the hierarchy and common exceptions. The Intermediate tab covers catching by level, custom exceptions, and chaining. The Expert tab covers ExceptionGroup, except*, and __cause__/__context__.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: catch Exception not BaseException, and order except clauses most-specific-first.
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 20 min
Required Reading
Exception Hierarchy — The Codex

The BaseException tree, Exception vs BaseException, common exceptions (ValueError/TypeError/KeyError/IndexError), catching by level, multiple types, custom exception classes, raise...from chaining, ExceptionGroup/except* (3.11+), and __cause__/__context__.

LESSON 23

The Walrus Operator (:=)

assignment expressions, while loops, comprehensions

The walrus operator := assigns inside an expression. The Beginner tab covers assign-and-test in one step. The Intermediate tab covers the while-loop read pattern and comprehensions. The Expert tab covers scope rules and prohibited forms.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: while (chunk := f.read(n)) — the canonical pattern. := needs parentheses and cannot replace = at top level.
⏱ Beginner: 20 min · Intermediate: 20 min · Expert: 20 min
Required Reading
Walrus Operator — The Codex

Assignment expressions (PEP 572), assign-and-test in conditions, the while-loop read pattern, file-chunk reading, comprehension use to avoid double computation, scope rules (binds to containing scope), and prohibited forms.

LESSON 24

File I/O

open(), modes, text vs binary, encodings, the io module, pathlib

Almost every real program touches files. The Beginner tab covers open() modes (the table of r/w/a/x/b/t), reading line by line, and writing. The Intermediate tab covers binary mode, encodings, the seek/tell API, and pathlib shortcuts. The Expert tab covers the io module's three-layer architecture (FileIO → BufferedReader → TextIOWrapper), newline translation, and why csv requires newline=''.

📚 🟩 Beginner, then 🔵 Intermediate. Both are essential for daily Python work.
Key focus: Focus on: always using 'with open(...) as f:' — never open and close manually. And always specify encoding='utf-8'. These two habits prevent the most common file I/O bugs.
⏱ Beginner: 40 min · Intermediate: 40 min · Expert: 25 min
Required Reading
File I/O — The Codex

open() modes table, reading (read/readline/readlines/iteration), writing (write/writelines), text vs binary mode, encoding='utf-8' and the errors argument, seek() and tell(), the io module's three layers, newline translation, and the newline='' requirement for csv.

pathlib — The Codex

Path objects, / operator for joining, read_text() and write_text(), exists()/is_file()/is_dir(), glob() and rglob(), and replacing os.path permanently.

LESSON 25

Modules & Packages

import system, __init__.py, sys.path, pip, venv, importlib

Python's 'batteries included' philosophy means the standard library provides almost everything you need — and pip gives access to hundreds of thousands of third-party packages. The Beginner tab covers import forms and packages. The Intermediate tab covers sys.path, the __main__ guard, pip and venv. The Expert tab covers relative imports, the full import protocol (finders, loaders, sys.modules), namespace packages, and circular import pitfalls.

📚 🟩 Beginner, then 🔵 Intermediate. The venv section is essential — use a virtual environment for every project.
Key focus: Focus on: the 'if __name__ == "__main__":' guard. This prevents your module's code from running when it's imported, and understanding it makes the import system click.
⏱ Beginner: 40 min · Intermediate: 40 min · Expert: 25 min
Required Reading
Modules & Packages — The Codex

import forms and aliases, packages and __init__.py, the module search path (sys.path), sys.modules cache, the __main__ guard, pip install and requirements.txt, virtual environments with venv, absolute vs relative imports (PEP 328), importlib for dynamic imports, namespace packages (PEP 420), and circular import solutions.

LESSON 26

Type Hints

Annotations, Optional/Union/|, generics, TypeVar, Protocols, mypy

Type hints don't change how Python runs — but they transform what your editor can catch, what tools like mypy can verify, and how readable your code is for other developers. Since PEP 484, they have become standard in professional Python. The Beginner tab covers basic function and variable annotations. The Intermediate tab covers Optional, Union, and the Python 3.10+ | operator. The Expert tab covers TypeVar, generics, Protocols (structural typing), and runtime introspection via __annotations__.

📚 🟩 Beginner, then 🔵 Intermediate. Install mypy and check a file after reading the Intermediate tab.
Key focus: Focus on: Optional[X] means 'X or None' — not 'this argument is optional'. And prefer the newer 'int | None' syntax (Python 3.10+) over 'Optional[int]' in new code.
⏱ Beginner: 35 min · Intermediate: 35 min · Expert: 30 min
Required Reading
Type Hints — The Codex

Function and variable annotations, built-in container generics (list[int], dict[str, int] — PEP 585), Optional and Union (PEP 484, PEP 604), the | union operator (Python 3.10+), TypeVar and generic functions, Generic classes, Protocols and structural typing (PEP 544), @runtime_checkable, mypy usage, __annotations__, get_type_hints(), and dataclasses using annotations.

LESSON 27

Concurrency

threading, multiprocessing, asyncio, the GIL, concurrent.futures

Knowing which concurrency model to use is one of the most valuable practical skills in Python. The Beginner tab explains the critical I/O-bound vs CPU-bound distinction and gives threading and asyncio examples. The Intermediate tab covers multiprocessing and concurrent.futures. The Expert tab explains the GIL in depth and PEP 703 (the experimental free-threaded build in Python 3.13+).

📚 🟩 Beginner tab is essential — the I/O vs CPU-bound distinction determines which model to use. Read all three tabs; the Expert tab on the GIL is illuminating.
Key focus: Focus on: the decision table. I/O-bound → threading or asyncio. CPU-bound → multiprocessing. Getting this wrong doesn't just fail to help — it actively makes things slower due to the GIL.
⏱ Beginner: 50 min · Intermediate: 40 min · Expert: 30 min
Required Reading
Concurrency — The Codex

I/O-bound vs CPU-bound (the core decision), threading.Thread and ThreadPoolExecutor, multiprocessing.Pool and ProcessPoolExecutor, asyncio event loop and async/await, the GIL and why it exists, concurrent.futures unified API, as_completed(), PEP 703 (free-threaded build, Python 3.13+).

asyncio — The Codex

async/await syntax, asyncio.run(), create_task() and gather(), wait_for() for timeouts, shield(), run_in_executor() for blocking code, and the event loop execution model.

LESSON 28

Testing

unittest, pytest, fixtures, parametrize, mocking, coverage

Automated tests are what allow you to change code confidently. The Beginner tab covers unittest — TestCase, assertion methods, assertRaises, and running tests. The Intermediate tab covers pytest (cleaner syntax, plain assert, fixtures, parametrize). The Expert tab covers unittest.mock in depth — Mock, MagicMock, patch(), patch-where-it-is-used, and the testing pyramid.

📚 🟩 Beginner (unittest), then 🔵 Intermediate (pytest). After reading both, write actual tests for one of your Stage 1 or 2 programs.
Key focus: Focus on: the 'patch where it is used, not where it is defined' rule. This is the single most common mocking mistake and understanding it saves hours of debugging.
⏱ Beginner: 40 min · Intermediate: 45 min · Expert: 35 min
Required Reading
Testing — The Codex

unittest and TestCase, assertion methods table, assertRaises, setUp/tearDown, pytest plain function style, @pytest.fixture, @pytest.mark.parametrize, unittest.mock.Mock, MagicMock, @patch, patch as context manager, assert_called_once_with(), call_count, and pytest --cov for coverage.

unittest — Standard Library Deep Dive

Full TestCase API, setUpClass/tearDownClass, subTest(), test discovery, unittest.mock in depth, MagicMock vs Mock, patch.object.

Stage 3 The Standard Library 11 deep-dives · 3 reading levels each · ~10 hours total

Python ships with 'batteries included' — a vast standard library that solves most common programming problems without installing anything. These 11 deep-dives cover the most important modules. Each page has three reading levels. In Stage 3, read Beginner and Intermediate tabs for each. The Expert tabs explain internals — read them when you encounter a specific situation that needs deeper understanding.

LESSON 29

os — Operating System Interface

Files, directories, environment variables, processes

The os module is the bridge between Python and the OS. Beginner tab: path manipulation, listing directories, environment variables. Intermediate tab: os.walk for recursive traversal, process operations, os.scandir (faster than listdir). Expert tab: file descriptors, os.stat, and platform differences.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: os.path.join() — then learn that pathlib replaces it. Understanding both means you can read older code and write new code correctly.
⏱ Beginner: 30 min · Intermediate: 30 min
Required Reading
os — The Codex

os.getcwd/chdir, os.path.join/exists/dirname/basename/splitext, os.listdir/makedirs/remove/rename, os.environ and os.getenv, os.walk for recursive directory traversal, os.scandir as the efficient alternative, and os.system/subprocess.

LESSON 30

pathlib — Modern File Paths

Path objects, /, glob, rglob — the replacement for os.path

pathlib is the modern way to work with file paths. Instead of os.path.join('data', 'file.csv'), you write Path('data') / 'file.csv'. Beginner tab: constructing paths, the / operator, read_text/write_text. Intermediate tab: glob/rglob for searching, exists/is_file/is_dir. Expert tab: PEP 428, the Path class hierarchy, and resolving symlinks.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: the / operator for building paths and .read_text()/.write_text() for simple file access. These two features make pathlib immediately useful.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
pathlib — The Codex

Path construction and concatenation with /, Path.home() and Path.cwd(), exists()/is_file()/is_dir(), mkdir(parents=True), read_text/write_text/read_bytes/write_bytes, glob() and rglob() for pattern search, stat(), resolve(), relative_to(), and PEP 428.

LESSON 31

json — Data Exchange

Serialise Python to JSON and back — the universal data format

JSON is the universal format for APIs and data files. Beginner: json.load() (file→Python), json.loads() (string→Python), json.dump() (Python→file), json.dumps() (Python→string). Intermediate: custom serialisation for non-standard types. Expert: JSON specification (RFC 8259), performance, and alternatives (orjson, ujson).

📚 🟩 Beginner tab covers all the daily-use cases.
Key focus: Focus on: load vs loads (file vs string). This trips up almost every beginner. load takes a file object; loads takes a string.
⏱ Beginner: 25 min · Intermediate: 20 min
Required Reading
json — The Codex

json.load() and json.loads(), json.dump() and json.dumps(), the type mapping table (Python ↔ JSON), indent= for pretty-printing, ensure_ascii=False for Unicode, custom serialisation with default=, and json.JSONDecodeError.

LESSON 32

re — Regular Expressions

Pattern matching, groups, substitution — the most powerful text tool

Regular expressions look cryptic at first but the core syntax is small. Beginner: re.search(), re.match(), re.findall(), basic patterns (., *, +, ?, [], ^, $). Intermediate: capturing groups, re.sub() for substitution, compiled patterns, and flags (re.IGNORECASE, re.MULTILINE). Expert: lookaheads, lookbehinds, non-greedy matching, and how the NFA engine works.

📚 🟩 Beginner, then 🔵 Intermediate. Practice writing patterns as you read.
Key focus: Focus on: re.search() vs re.match(). search() looks anywhere in the string; match() only at the start. This is the source of most regex bugs.
⏱ Beginner: 35 min · Intermediate: 35 min · Expert: 25 min
Required Reading
re — The Codex

Pattern syntax reference (character classes, quantifiers, anchors, groups), re.search/match/findall/finditer/sub/split, named groups (?P), compiled patterns with re.compile(), flags, lookahead (?=) and lookbehind (?<=), non-greedy *? and +?, and the NFA engine model.

LESSON 33

datetime — Dates & Times

date, time, datetime, timedelta, timezones — time is hard

Time is one of the genuinely tricky problems in software. Beginner: date, time, datetime objects, strftime/strptime formatting. Intermediate: timedelta for arithmetic, timezone-aware datetimes with ZoneInfo (Python 3.9+). Expert: naive vs aware datetimes, epoch time, the complexity of leap seconds and TAI.

📚 🟩 Beginner, then 🔵 Intermediate. Pay attention to the naive vs aware distinction.
Key focus: Focus on: always use timezone-aware datetimes in production code. Naive datetimes (no timezone) cause subtle bugs when code runs in different timezones or during daylight saving transitions.
⏱ Beginner: 30 min · Intermediate: 30 min
Required Reading
datetime — The Codex

datetime.date, datetime.time, datetime.datetime, datetime.timedelta, strftime() format codes, strptime() for parsing, datetime.now() vs datetime.utcnow(), timezone-aware datetimes, ZoneInfo (Python 3.9+), and naive vs aware datetimes.

LESSON 34

collections — Specialised Containers

Counter, defaultdict, deque, namedtuple, OrderedDict, ChainMap

The collections module provides specialised containers for the cases where list and dict aren't enough. Beginner: Counter (frequency counting in one line) and defaultdict (eliminates KeyError for missing keys). Intermediate: deque (O(1) appends from both ends), namedtuple (readable field names on tuples). Expert: ChainMap, UserDict/UserList, and the collections.abc abstract base classes.

📚 🟩 Beginner (Counter + defaultdict) immediately useful. 🔵 Intermediate for deque and namedtuple.
Key focus: Focus on: Counter. It replaces a surprisingly large amount of manual counting code with one line. Counter(words).most_common(10) replaces 15 lines of loop logic.
⏱ Beginner: 30 min · Intermediate: 30 min
Required Reading
collections — The Codex

Counter and most_common(), Counter arithmetic (add, subtract, intersection, union), defaultdict with factory functions, deque with maxlen and appendleft/popleft, namedtuple vs dataclass (when to use each), OrderedDict and move_to_end(), ChainMap for layered lookups, and collections.abc ABCs.

LESSON 35

itertools — Iterator Toolkit

chain, product, combinations, groupby — composable sequence tools

itertools provides fast, memory-efficient building blocks for working with sequences. Beginner: chain (flatten iterables), islice (slice without a list), product (Cartesian product). Intermediate: permutations/combinations, groupby (group consecutive elements by key), accumulate. Expert: itertools recipes from the official docs, and the mathematical concept of iterator algebra.

📚 🟩 Beginner, then 🔵 Intermediate. Use the official recipes in Expert as a reference.
Key focus: Focus on: itertools.chain() and itertools.groupby(). chain is immediately useful for flattening nested data. groupby is essential for data processing but has a gotcha — the data must be sorted by the key first.
⏱ Beginner: 25 min · Intermediate: 30 min · Expert: 20 min
Required Reading
itertools — The Codex

chain() and chain.from_iterable(), islice() for memory-efficient slicing, product() for Cartesian products, permutations() and combinations(), groupby() and the sort-before-group requirement, accumulate(), takewhile() and dropwhile(), cycle() and repeat(), and the official itertools recipes.

LESSON 36

sys — System Parameters

Command-line args, stdin/stdout, module search, interpreter info

The sys module gives you access to the interpreter itself. Beginner: sys.argv for command-line arguments, sys.exit() for clean termination. Intermediate: sys.stdin/stdout/stderr, sys.path (the module search path), sys.modules (the cache). Expert: sys.getrefcount, frame objects, and CPython-specific internals.

📚 🟩 Beginner tab covers the daily-use cases.
Key focus: Focus on: sys.argv. This is how command-line scripts receive arguments — every script that users run from the terminal uses this.
⏱ Beginner: 20 min · Intermediate: 25 min
Required Reading
sys — The Codex

sys.argv and command-line parsing, sys.exit() and exit codes, sys.stdin/stdout/stderr and redirecting output, sys.path and how Python finds modules, sys.modules cache and import mechanics, sys.version and sys.platform, sys.getrecursionlimit/setrecursionlimit, and sys.getrefcount for debugging.

LESSON 37

asyncio — Async I/O Deep Dive

Event loop, coroutines, tasks, gather, timeout, executor

This lesson goes deeper than the Concurrency overview in Stage 2. Beginner: async/await syntax, asyncio.run(), simple coroutines. Intermediate: asyncio.create_task() and gather() for running multiple coroutines concurrently, wait_for() for timeouts. Expert: the event loop execution model, run_in_executor() for blocking code, and the history of async in Python (PEP 492, PEP 3156).

📚 🟩 Beginner. 🔵 Intermediate (create_task + gather). 🔴 Expert when building production async code.
Key focus: Focus on: await blocks until a result is ready, but yields control to the event loop so other coroutines can run while waiting. This is the mental model that makes async/await click.
⏱ Beginner: 35 min · Intermediate: 35 min · Expert: 25 min
Required Reading
asyncio — The Codex

async def and await syntax, asyncio.run() as the entry point, asyncio.create_task() for concurrent execution, asyncio.gather() for multiple tasks, asyncio.wait_for() with timeout, asyncio.shield(), loop.run_in_executor() for blocking I/O, the event loop model, and aiohttp as a real-world async HTTP client pattern.

LESSON 38

logging — Production Diagnostics

Levels, loggers, handlers, formatters, structured logging

Every production application needs logging. print() is not the answer: it has no severity levels, no filtering, and no way to write to files or external systems. Beginner: logging.basicConfig(), the five log levels (DEBUG through CRITICAL), and basic usage. Intermediate: named loggers (hierarchical), handlers (FileHandler, StreamHandler), and formatters. Expert: the logging architecture (LogRecord pipeline), structured logging with dictConfig.

📚 🟩 Beginner (basicConfig + levels). 🔵 Intermediate (named loggers + handlers) for production code.
Key focus: Focus on: using logging.getLogger(__name__) instead of the root logger. This creates a named logger per module, giving you precise control over which modules log what and at what level.
⏱ Beginner: 25 min · Intermediate: 30 min
Required Reading
logging — The Codex

Log levels (DEBUG/INFO/WARNING/ERROR/CRITICAL), logging.basicConfig(), logging.getLogger(__name__), FileHandler and StreamHandler, Formatter strings, the logging hierarchy and propagation, logging.config.dictConfig() for production configuration, structured JSON logging, and the LogRecord pipeline.

LESSON 39

unittest — Testing Framework

TestCase, assertions, setUp/tearDown, mocking, test discovery

While pytest is the modern default, unittest is built in and understanding it matters — many existing codebases use it, and unittest.mock is essential regardless of which runner you use. Beginner: TestCase, all assertion methods (assertEqual through assertAlmostEqual), assertRaises. Intermediate: setUp/tearDown lifecycle, test discovery, subTest for parametrised tests. Expert: Mock, MagicMock, patch(), patch.object(), the unittest architecture.

📚 🟩 Beginner (TestCase + assertions). 🔵 Intermediate (setUp + discovery). 🔴 Expert (mock architecture).
Key focus: Focus on: setUp runs before each test, not once. If you want one-time setup, use setUpClass. This is the most common unittest mistake that causes tests to interfere with each other.
⏱ Beginner: 30 min · Intermediate: 30 min · Expert: 30 min
Required Reading
unittest — The Codex

TestCase class and structure, assertion methods (assertEqual, assertTrue, assertIn, assertRaises, assertAlmostEqual), setUp/tearDown vs setUpClass/tearDownClass, @unittest.skip, test discovery with python -m unittest discover, subTest() for parametrised cases, unittest.mock.Mock/MagicMock, patch() as decorator and context manager, call_args and assert_called_once_with().

LESSON 40

functools — Higher-Order Function Tools

lru_cache, partial, reduce, wraps, cached_property

functools provides tools for working with functions and callables. Beginner: @lru_cache for instant memoisation and partial() for fixing arguments. Intermediate: reduce(), wraps() for decorators, and cached_property. Expert: singledispatch for function overloading and total_ordering. This module turns many multi-line patterns into one-liners.

📚 🟩 Beginner (lru_cache + partial) is immediately useful.
Key focus: Focus on: @lru_cache — adding one line above a recursive function can make it thousands of times faster through automatic memoisation.
⏱ Beginner: 25 min · Intermediate: 30 min
Required Reading
functools — The Codex

@lru_cache and @cache for memoisation, partial() for argument fixing, reduce() for folding, @wraps for decorators, cached_property, singledispatch for type-based dispatch, and total_ordering.

LESSON 41

csv — Reading & Writing CSV

reader, writer, DictReader, DictWriter, dialects

CSV is the universal format for tabular data exchange. Beginner: csv.reader and csv.writer for basic row-by-row processing. Intermediate: DictReader and DictWriter for working with named columns, and the critical newline='' requirement. Expert: dialects, quoting rules, and handling messy real-world CSV files.

📚 🟩 Beginner, then 🔵 Intermediate (DictReader). Always open with newline=''.
Key focus: Focus on: always open CSV files with newline='' — omitting it causes blank rows on Windows. And prefer DictReader for readable, column-name-based access.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
csv — The Codex

csv.reader and csv.writer, DictReader and DictWriter for named columns, the newline='' requirement, delimiters and dialects, quoting rules (QUOTE_MINIMAL, QUOTE_ALL), and handling messy CSV data.

LESSON 42

subprocess — Running External Programs

run(), check_output, pipes, shell safety

subprocess runs external programs from Python. Beginner: subprocess.run() with capture_output to call a command and read its output. Intermediate: checking return codes, passing input, and piping between processes. Expert: Popen for fine-grained control, and the critical security rule — never use shell=True with untrusted input.

📚 🟩 Beginner, then 🔵 Intermediate. Pay attention to the shell=True security warning.
Key focus: Focus on: passing arguments as a list (['ls', '-l']) rather than a string with shell=True — the list form is safe from shell injection.
⏱ Beginner: 30 min · Intermediate: 30 min
Required Reading
subprocess — The Codex

subprocess.run() with capture_output and text=True, check=True for error handling, passing stdin, piping between processes, Popen for streaming, and why shell=True is dangerous with untrusted input.

LESSON 43

argparse — Command-Line Arguments

parsers, positional/optional args, types, subcommands

argparse turns command-line arguments into a clean Python interface with automatic help. Beginner: creating a parser and adding arguments. Intermediate: types, choices, nargs, and subcommands. Expert: custom types, mutually exclusive groups, and parser composition.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: positional args are required; optional args (--name) are not. Run examples in a real terminal.
⏱ Beginner: 25 min · Intermediate: 30 min
Required Reading
argparse — The Codex

ArgumentParser, add_argument, positional vs optional arguments, action=store_true, type conversion, choices, nargs, subcommands with add_subparsers, custom type callables, mutually exclusive groups, and parent parsers.

LESSON 44

math — Mathematical Functions

constants, rounding, trig, logs, float safety

The math module provides standard mathematical functions. Beginner: constants, sqrt, powers, and rounding. Intermediate: trigonometry (in radians!), logarithms, and float-safety tools like isclose. Expert: IEEE 754 and choosing decimal or fractions for exact arithmetic.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: trig functions use radians (convert with math.radians), and never compare floats with == (use math.isclose).
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
math — The Codex

Constants (pi, e, inf, nan), sqrt and powers, floor/ceil/trunc, factorial/comb/perm/gcd/lcm, trigonometry in radians, logarithms, math.isclose for float comparison, fsum, isqrt, and IEEE 754 floating-point.

LESSON 45

random — Random Numbers

random/randint/choice, shuffle, sample, distributions, seeding

The random module generates pseudo-random numbers. Beginner: random floats, integers, and picking from sequences. Intermediate: distributions and reproducible seeding. Expert: the Mersenne Twister and why secrets must be used for security.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: randint includes both ends; random is NOT secure — use the secrets module for tokens and passwords.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
random — The Codex

random(), uniform(), randint vs randrange, choice/shuffle/sample/choices, weighted choices, statistical distributions (gauss, normalvariate), seeding for reproducibility, independent Random() instances, the Mersenne Twister, and why random is not cryptographically secure.

LESSON 46

contextlib — with-Statement Utilities

@contextmanager, suppress, redirect_stdout, ExitStack

contextlib provides tools for context managers. Beginner: @contextmanager turns a generator into a context manager. Intermediate: suppress, closing, and redirect_stdout. Expert: ExitStack for dynamic context management and the pop_all ownership pattern.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: @contextmanager — setup before yield, cleanup after, wrapped in try/finally.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
contextlib — The Codex

@contextmanager decorator, setup/yield/cleanup structure, suppress for ignoring exceptions, closing(), redirect_stdout and redirect_stderr, ExitStack for dynamic context managers, nullcontext, pop_all() ownership transfer, and asynccontextmanager.

LESSON 47

secrets — Cryptographically Secure Random

token generation, passwords, constant-time compare

secrets generates cryptographically secure random values. Beginner: why secrets not random, and generating tokens. Intermediate: passwords, PINs, and constant-time comparison. Expert: os.urandom, entropy sources, and token sizing.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: anything an attacker must not guess uses secrets, never random. secrets has no seed() by design.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
secrets — The Codex

Why secrets vs random, token_urlsafe/token_hex/token_bytes, secure passwords and OTPs with secrets.choice, compare_digest for constant-time comparison, os.urandom, and token sizing guidance.

LESSON 48

hashlib — Secure Hashes

SHA-256, file hashing, password hashing, HMAC

hashlib computes cryptographic hashes. Beginner: SHA-256 basics and hashing files for integrity. Intermediate: password hashing with pbkdf2_hmac/scrypt and choosing algorithms. Expert: salts, peppers, HMAC, and BLAKE2 keyed hashing.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: never use plain sha256 for passwords — use pbkdf2_hmac or scrypt with a per-password salt.
⏱ Beginner: 25 min · Intermediate: 30 min
Required Reading
hashlib — The Codex

SHA-256 and hexdigest, hashing bytes, hashing files in chunks, pbkdf2_hmac and scrypt for passwords, salts, algorithm choice, HMAC for authentication, BLAKE2 keyed hashing, and why md5/sha1 are broken.

LESSON 49

statistics — Mathematical Statistics

mean, median, stdev, NormalDist, regression

The statistics module provides everyday statistics without NumPy. Beginner: mean, median, mode, variance, standard deviation. Intermediate: the NormalDist class and type precision. Expert: numerical accuracy, correlation, and linear regression.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: mean is distorted by outliers; median resists them. Use sample stdev for samples, pstdev for full populations.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
statistics — The Codex

mean/median/mode, fmean, variance and standard deviation, sample vs population, the NormalDist class (cdf, inv_cdf, from_samples), quantiles, type preservation for Decimal/Fraction, correlation, covariance, and linear_regression.

LESSON 50

pickle — Object Serialization

dumps/loads, files, the security risk, pickle vs JSON

pickle serializes almost any Python object to bytes. Beginner: pickling and unpickling, saving to files. Intermediate: the critical security risk and pickle vs JSON. Expert: protocols, __getstate__/__setstate__, and alternatives.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: NEVER unpickle data from an untrusted source — it can execute arbitrary code. Use JSON across trust boundaries.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
pickle — The Codex

pickle.dumps/loads and dump/load, binary mode, preserving tuples/sets/datetimes/custom classes, the arbitrary-code-execution security risk, signing pickles with hmac, pickle vs JSON, protocols 0-5, and __getstate__/__setstate__.

LESSON 51

sqlite3 — Built-in SQL Database

connect, query, parameters, transactions, Row factory

sqlite3 gives Python a complete SQL database with zero setup. Beginner: connecting, creating tables, inserting and reading, and commit(). Intermediate: safe parameterised queries, the Row factory, and transactions. Expert: type adapters, PRAGMAs, and scaling limits.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: always use ? placeholders, never f-strings (SQL injection), and remember you must commit() to save.
⏱ Beginner: 30 min · Intermediate: 30 min
Required Reading
sqlite3 — The Codex

connect and cursor, CREATE TABLE, INSERT/SELECT/UPDATE/DELETE, commit(), fetchall/fetchone, ? placeholders to prevent SQL injection, executemany, sqlite3.Row for named columns, transactions with conn, type adapters, PRAGMA foreign_keys, and DB-API 2.0.

LESSON 52

time — Time Access and Conversions

timestamps, sleep, perf_counter, clocks

The time module provides low-level clock access. Beginner: timestamps, sleep(), and the time-vs-datetime distinction. Intermediate: measuring with perf_counter, formatting, and choosing the right clock. Expert: clock characteristics and nanosecond precision.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: never measure durations with time.time() (it can jump) — use perf_counter or monotonic.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
time — The Codex

time.time() timestamps, sleep(), localtime/gmtime/ctime, perf_counter for benchmarking, monotonic for timeouts, process_time for CPU time, strftime/strptime, get_clock_info, and the _ns nanosecond variants.

LESSON 53

shutil — High-Level File Operations

copy trees, move, rmtree, archives, disk usage

shutil handles whole-file and whole-directory operations. Beginner: copying files and directory trees. Intermediate: archives (zip/tar), disk usage, and which. Expert: copy fidelity, move semantics, and fast-copy syscalls.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: rmtree is permanent and recursive (like rm -rf) — double-check the path before calling it.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
shutil — The Codex

copy/copy2/copyfile fidelity levels, copytree with dirs_exist_ok and ignore_patterns, move, rmtree, make_archive and unpack_archive for zip/tar, disk_usage, shutil.which to find executables, and move atomicity across filesystems.

LESSON 54

copy — Shallow and Deep Copy

shallow vs deep copy, the memo dict, __deepcopy__

The copy module duplicates objects. Beginner: why = is not a copy and how to make a shallow copy. Intermediate: shallow vs deep copy and customising with __copy__/__deepcopy__. Expert: the memo dictionary and the pickle connection.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: shallow copy shares nested objects; deep copy duplicates them. Use deepcopy for independent nested data.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
copy — The Codex

assignment vs copying, identity vs equality, copy.copy shallow copies, the shallow-copy trap with nested objects, copy.deepcopy for full independence, cyclic reference handling, __copy__/__deepcopy__ customisation, the memo dictionary, and the __reduce_ex__ pickle connection.

LESSON 55

concurrent.futures — High-Level Parallelism

ThreadPoolExecutor, ProcessPoolExecutor, Future, map

concurrent.futures runs functions in parallel with one uniform API. Beginner: the executor and map. Intermediate: futures, submit, and the I/O-bound vs CPU-bound choice. Expert: Future internals, callbacks, and the GIL's future.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: I/O-bound work uses threads; CPU-bound work uses processes. The GIL is why the distinction matters.
⏱ Beginner: 25 min · Intermediate: 30 min
Required Reading
concurrent.futures — The Codex

ThreadPoolExecutor and ProcessPoolExecutor, executor.map, submit and Future objects, as_completed, result/done/exception, I/O-bound vs CPU-bound and the GIL, picklability requirements, callbacks, wait, and free-threading (PEP 703).

LESSON 56

queue — Thread-Safe Queues

Queue, producer-consumer, LifoQueue, PriorityQueue, join

The queue module passes work between threads safely. Beginner: why thread-safe and the producer-consumer pattern. Intermediate: LIFO and priority variants, task_done and join. Expert: blocking semantics, SimpleQueue, and shutdown.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: get() blocks on an empty queue by default — that blocking is what powers producer-consumer.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
queue — The Codex

thread-safe Queue, put and get, blocking behaviour, the producer-consumer pattern with sentinels, LifoQueue and PriorityQueue, priority tiebreakers, task_done and join for completion tracking, get_nowait, SimpleQueue, and shutdown (3.13).

LESSON 57

socket — Low-Level Networking

TCP/UDP, client, server, selectors

The socket module is Python's direct interface to the network. Beginner: what a socket is and a TCP client. Intermediate: the TCP server lifecycle, UDP, and timeouts. Expert: non-blocking I/O, selectors, and the path to asyncio.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: sockets send bytes not strings, and the bind/listen/accept/recv server lifecycle.
⏱ Beginner: 30 min · Intermediate: 30 min
Required Reading
socket — The Codex

sockets as network endpoints, TCP vs UDP, AF_INET and SOCK_STREAM, a TCP client with connect/sendall/recv, the bind/listen/accept server lifecycle, UDP sendto/recvfrom, timeouts, send vs sendall, blocking vs non-blocking, selectors, socketserver, and the path to asyncio.

LESSON 58

http.server — Built-in HTTP Server

instant file server, BaseHTTPRequestHandler, WSGI

http.server provides a ready-made HTTP server. Beginner: the one-command file server and HTTPServer in code. Intermediate: custom handlers with do_GET/do_POST. Expert: the handler lifecycle, WSGI, and production servers.

📚 🟩 Beginner, then 🔵 Intermediate.
Key focus: Focus on: the fixed response order (send_response, send_header, end_headers, body) and that this is for development only.
⏱ Beginner: 25 min · Intermediate: 25 min
Required Reading
http.server — The Codex

python -m http.server file serving, --bind and --directory, HTTPServer and SimpleHTTPRequestHandler, custom handlers with do_GET/do_POST, the send_response/send_header/end_headers/body order, reading request bodies, ThreadingHTTPServer, why it is not for production, the handler lifecycle, and WSGI (PEP 3333).

Stage 4 Concepts That Cross Languages 15 concept pages · ~6 hours total

These pages connect Python to programming in general. Each concept page explains the underlying idea in language-agnostic terms — showing how Python implements it, and how other languages approach the same problem. This stage deepens your understanding beyond Python syntax and into how programming itself works.

LESSON 59

Concept: Variables

How variables work in programming languages

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Variables — Concepts

How variables work across languages, Python vs JavaScript vs Java comparison.

LESSON 60

Concept: Data Types

Type systems: static, dynamic, strong, weak

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Data Types — Concepts

Static vs dynamic typing, strong vs weak typing, and where Python sits.

LESSON 61

Concept: Operators

Arithmetic, comparison, logical, bitwise across languages

📚 🟩 Beginner tab.
⏱ 15 min
Required Reading
Operators — Concepts

Operators across Python, JavaScript, Java, and Go.

LESSON 62

Concept: Control Flow

Decision making in programs — universally

📚 🟩 Beginner tab.
⏱ 15 min
Required Reading
Control Flow — Concepts

How if/else and switch/match work across languages.

LESSON 63

Concept: Loops

for, while, iterators — the loop concept

📚 🟩 Beginner tab.
⏱ 15 min
Required Reading
Loops — Concepts

for vs while, iteration protocols, and how Python loops differ from C-style loops.

LESSON 64

Concept: Functions

First-class functions, higher-order functions

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Functions — Concepts

Functions as values, higher-order functions, and Python vs other languages.

LESSON 65

Concept: Scope

How names resolve in different languages

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Scope — Concepts

Lexical scope, dynamic scope, and Python's LEGB compared to JavaScript and Java.

LESSON 66

Concept: Classes

OOP across languages — what a class actually is

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Classes — Concepts

How classes work in Python vs Java vs JavaScript.

LESSON 67

Concept: Objects

Object identity, equality, and the object model

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Objects — Concepts

Object identity vs equality, Python's everything-is-an-object model.

LESSON 68

Concept: Inheritance

Single, multiple, prototype — inheritance models

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Inheritance — Concepts

Single vs multiple inheritance, Python MRO, JavaScript prototypes, Java extends.

LESSON 69

Concept: Error Handling

Exceptions vs error codes — language approaches

📚 🟩 Beginner tab.
⏱ 15 min
Required Reading
Error Handling — Concepts

Exception-based vs error-return models, Go errors vs Python exceptions.

LESSON 70

Concept: Modules

Module systems across languages

📚 🟩 Beginner tab.
⏱ 15 min
Required Reading
Modules — Concepts

How Python, JavaScript, Java, and Go organise code into modules.

LESSON 71

Concept: Concurrency

Threads, async, actors — concurrency models

📚 🟩 Beginner tab.
⏱ 25 min
Required Reading
Concurrency — Concepts

Threading, event loops, actors, and CSP — how different languages handle concurrent execution.

LESSON 72

Concept: Recursion

Recursive thinking, tail calls, stack depth

📚 🟩 Beginner tab.
⏱ 20 min
Required Reading
Recursion — Concepts

Recursion vs iteration, call stack, Python's recursion limit, and tail call optimisation in other languages.

LESSON 73

Concept: Arrays

Arrays vs lists — memory model and performance

📚 🟩 Beginner tab.
⏱ 15 min
Required Reading
Arrays — Concepts

Fixed vs dynamic arrays, Python lists vs numpy arrays, memory layout.

Stage 5 Build Real Things — 14 Projects 60 projects · Beginner → Intermediate → Advanced · ~16 hours total

This is where everything clicks. Reading about code is not the same as writing it. Each project has three tabs: Walkthrough (explains every decision), Full Code (the complete working program), and Extend It (ideas to push further). Do them in the order shown — difficulty increases gradually. Aim to do at least 2 beginner, 2 intermediate, and 1 advanced project before considering Stage 5 complete.

LESSON 74

Number Guessing Game

Beginner — variables, loops, conditionals, user input

Your first complete interactive program. The computer picks a random number; the user guesses. After each guess, the program says 'too high', 'too low', or 'correct'. Applies: variables, while loops, if/elif/else, input(), and the random module.

📚 🛠 Walkthrough tab fully → Full Code tab → attempt Extend It.
Key focus: Focus on: writing the while loop and the conditional logic yourself before looking at the Full Code tab.
⏱ ~45 min
Required Reading
Number Guessing Game — The Codex

Complete walkthrough, full working code, and 5 extension challenges.

LESSON 75

Calculator

Beginner — functions, error handling, clean interface

A command-line calculator for addition, subtraction, multiplication, and division. Applies: functions (one per operation), error handling for division by zero, a user menu loop, and string formatting.

📚 🛠 Walkthrough tab → Full Code → Extend It.
Key focus: Focus on: structuring your code into named functions before writing the menu. Good function design makes the calculator trivially easy to extend.
⏱ ~45 min
Required Reading
Calculator — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 76

Unit Converter

Beginner — dictionaries, functions, user menus

Converts between km and miles, kg and pounds, Celsius and Fahrenheit, and more. Applies: dictionaries for conversion factors, functions, nested menus, and input validation.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: using a dictionary of conversion factors rather than if/elif chains. This is the cleaner data-driven approach.
⏱ ~50 min
Required Reading
Unit Converter — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 77

Word Counter

Beginner — string processing, file I/O, collections

Reads a text file and reports word count, character count, most common words, and average word length. Applies: file I/O (open, read), string methods (.split(), .lower()), Counter from collections.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: using Counter for frequency counting instead of a manual dict-update loop. Counter is exactly the right tool here.
⏱ ~50 min
Required Reading
Word Counter — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 78

Password Generator

Beginner — random module, string manipulation, customisation

Generates secure random passwords with configurable length, character sets (uppercase, lowercase, digits, symbols), and strength checking. Applies: random.choices(), string module constants, user input with validation.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: using random.choices() with a weights= parameter rather than concatenating character lists.
⏱ ~45 min
Required Reading
Password Generator — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 79

To-Do List

Intermediate — file persistence, OOP, CRUD

A complete task manager: add, complete, delete, and list tasks, with tasks saved to a JSON file so they persist between runs. Applies: OOP (Task and TaskManager classes), JSON file I/O, list operations, and a command menu.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: the save/load cycle — how the program reads from and writes to the JSON file on every operation. This is the core persistence pattern for Python applications.
⏱ ~70 min
Required Reading
To-Do List — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 80

Contact Book

Intermediate — JSON storage, search, OOP

An address book that stores contacts (name, phone, email, address) to a JSON file, with search, add, update, and delete. Applies: OOP (Contact and ContactBook classes), JSON serialisation/deserialisation, search across multiple fields.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: designing the data model (what fields does a Contact have?) before writing any code. Design first, code second.
⏱ ~70 min
Required Reading
Contact Book — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 81

Budget Tracker

Intermediate — datetime, file I/O, data aggregation

Tracks income and expenses with categories and dates, calculates totals and balances, and generates category summaries. Applies: datetime for transaction dates, JSON persistence, list comprehensions for filtering, and formatted reports.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: using list comprehensions to filter transactions by category, date range, or type. This replaces multiple loops with clean one-liners.
⏱ ~75 min
Required Reading
Budget Tracker — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 82

Quiz Engine

Intermediate — JSON data files, random selection, scoring

A quiz system that loads questions from a JSON file, presents them in random order, tracks the score, and shows a results summary. Applies: JSON loading, random.shuffle(), score tracking, and separating data (questions.json) from logic (quiz.py).

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: the separation of data and logic. The questions live in questions.json; the quiz logic is in quiz.py. Changing the questions doesn't require touching the code.
⏱ ~65 min
Required Reading
Quiz Engine — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 83

Text Adventure Game

Intermediate — state machines, OOP, game loops

A text-based adventure where the player moves between rooms, picks up items, and solves simple puzzles. Applies: OOP (Room, Player, Item classes), a game loop, state management, and dict-based world definition.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: how the world is represented as a dictionary of Room objects linked by direction. This is a state machine — the fundamental pattern for all game engines.
⏱ ~80 min
Required Reading
Text Adventure Game — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 84

Markdown to HTML

Advanced — regular expressions, file parsing, text transformation

A Markdown converter that transforms headers (# →

), bold/italic (**text** → ), links, and paragraphs into valid HTML. Applies: regular expressions for pattern matching and substitution, multi-pass text processing, and file I/O.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: processing the document in multiple passes — one regex per Markdown feature. Trying to handle everything in one pass is the mistake that makes parsers unreadable.
⏱ ~90 min

Required Reading
Markdown to HTML — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 85

Flashcard App

Advanced — spaced repetition, JSON persistence, OOP

A flashcard system implementing a simplified spaced repetition algorithm (SM-2): cards you get right appear less frequently; cards you get wrong appear sooner. Applies: OOP, datetime arithmetic for scheduling, JSON persistence.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: the spaced repetition scheduling logic — how the algorithm calculates the next review date based on difficulty. This is the most algorithmically interesting part.
⏱ ~90 min
Required Reading
Flashcard App — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 86

Data Analyser

Advanced — CSV processing, statistics, reporting

Loads a CSV file, computes statistics (mean, median, mode, standard deviation, min, max) for numeric columns, identifies outliers, and generates a text report. Applies: the csv module, statistics module, list comprehensions for filtering.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: writing the data loading and cleaning logic before the statistical analysis. Data is almost always messier than expected.
⏱ ~90 min
Required Reading
Data Analyser — The Codex

Complete walkthrough, full working code, and extension challenges.

LESSON 87

Simple Web Server

Advanced — http.server, sockets, HTTP, request handling

A working HTTP server built from Python's http.server module, serving files, handling routing, and returning JSON responses. This project demystifies the web — you'll understand what happens between a browser URL and a web page. Applies: http.server.BaseHTTPRequestHandler, socket basics, HTTP status codes, MIME types.

📚 🛠 Walkthrough → Full Code → Extend It.
Key focus: Focus on: the request/response cycle. A browser sends an HTTP request (method + path + headers). Your server reads it, decides what to return, and sends a response (status code + headers + body). Everything else is detail.
⏱ ~100 min
Required Reading
Simple Web Server — The Codex

Complete walkthrough, full working code, and extension challenges.

Stage 6 Practice & Experimentation 2 resources · Ongoing

Stages 0–5 give you structured knowledge. Stage 6 is where you apply it freely — experimenting, testing ideas, and checking your understanding against real examples. Use these two resources as ongoing companions throughout your Python journey, not just after completing Stage 5.

LESSON 88

Python Playground

Run Python code in your browser — no installation needed

The Python Playground lets you run Python code directly in your browser using Pyodide (CPython compiled to WebAssembly). Use it to test small ideas, verify your understanding of a concept, or experiment without touching your local setup. All 14 Python snippets from Stage 6 are runnable here.

📚 ▶ No tabs — just run code. Start with the pre-loaded examples, then modify them.
Key focus: Use the playground whenever you read a concept and think "I wonder what happens if I...". The fastest way to learn is to test your predictions.
⏱ Ongoing
Required Reading
Python Playground — The Codex

Browser-based Python runtime via Pyodide. Run any Python 3 code without installation.

LESSON 89

Python Snippets

14 copy-paste ready code examples for common Python tasks

14 real-world Python snippets covering the most common tasks: reading/writing files, working with JSON, making HTTP requests, sorting with custom keys, using dataclasses, string formatting, and more. All snippets are runnable in the browser via the Try It button.

📚 📋 Browse and run the snippets. Use them as reference when writing your own code.
Key focus: Use these snippets as patterns. When you need to do something in Python and can't remember the exact syntax, check here before searching the web.
⏱ Ongoing
Required Reading
Python Snippets — The Codex

14 runnable Python code snippets for common real-world tasks.