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
Course Stages — Recommended sequential study
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.
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.
What programming languages are, why Python exists, real-world uses, and a side-by-side comparison with Java and C++.
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.
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.
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.
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.
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.
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.
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.
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.
Case conversion, whitespace stripping, find/index/replace, split and join, validation methods (isdigit/isalpha), alignment (zfill/ljust/center), removeprefix/removesuffix, and string immutability.
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.
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.
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__.
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.
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.
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.
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().
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).
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.
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.
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.
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__.
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.
Closure conditions, captured free variables, the nonlocal keyword, __closure__ and cell objects, memoisation, and CPython MAKE_CELL/STORE_DEREF/LOAD_DEREF bytecode.
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.
The @syntax equivalence, functools.wraps, timing and retry decorators, decorator factories with arguments, stacking, class decorators, @dataclass internals, and the descriptor protocol behind @property.
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.
yield vs return, lazy evaluation, memory efficiency, infinite generators, generator pipelines, yield from delegation, send() for coroutines, and CPython gi_frame internals.
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.
The with statement, __enter__/__exit__ protocol, @contextlib.contextmanager, contextlib.suppress, ExitStack for dynamic management, and async with.
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.
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.
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.
@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.
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.
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.
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.
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.
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.
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.
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.
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.
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+).
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__.
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__.
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.
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.
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=''.
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.
Path objects, / operator for joining, read_text() and write_text(), exists()/is_file()/is_dir(), glob() and rglob(), and replacing os.path permanently.
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.
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.
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__.
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.
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+).
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+).
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.
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.
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.
Full TestCase API, setUpClass/tearDownClass, subTest(), test discovery, unittest.mock in depth, MagicMock vs Mock, patch.object.
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.
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.
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.
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.
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.
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).
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.
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.
Pattern syntax reference (character classes, quantifiers, anchors, groups), re.search/match/findall/finditer/sub/split, named groups (?P
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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().
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.
@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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
@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.
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.
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.
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.
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.
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.
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.
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.
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__.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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).
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.
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.
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.
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).
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.
Concept: Variables
How variables work in programming languages
How variables work across languages, Python vs JavaScript vs Java comparison.
Concept: Data Types
Type systems: static, dynamic, strong, weak
Static vs dynamic typing, strong vs weak typing, and where Python sits.
Concept: Operators
Arithmetic, comparison, logical, bitwise across languages
Operators across Python, JavaScript, Java, and Go.
Concept: Control Flow
Decision making in programs — universally
How if/else and switch/match work across languages.
Concept: Loops
for, while, iterators — the loop concept
for vs while, iteration protocols, and how Python loops differ from C-style loops.
Concept: Functions
First-class functions, higher-order functions
Functions as values, higher-order functions, and Python vs other languages.
Concept: Scope
How names resolve in different languages
Lexical scope, dynamic scope, and Python's LEGB compared to JavaScript and Java.
Concept: Classes
OOP across languages — what a class actually is
How classes work in Python vs Java vs JavaScript.
Concept: Objects
Object identity, equality, and the object model
Object identity vs equality, Python's everything-is-an-object model.
Concept: Inheritance
Single, multiple, prototype — inheritance models
Single vs multiple inheritance, Python MRO, JavaScript prototypes, Java extends.
Concept: Error Handling
Exceptions vs error codes — language approaches
Exception-based vs error-return models, Go errors vs Python exceptions.
Concept: Modules
Module systems across languages
How Python, JavaScript, Java, and Go organise code into modules.
Concept: Concurrency
Threads, async, actors — concurrency models
Threading, event loops, actors, and CSP — how different languages handle concurrent execution.
Concept: Recursion
Recursive thinking, tail calls, stack depth
Recursion vs iteration, call stack, Python's recursion limit, and tail call optimisation in other languages.
Concept: Arrays
Arrays vs lists — memory model and performance
Fixed vs dynamic arrays, Python lists vs numpy arrays, memory layout.
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.
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.
Complete walkthrough, full working code, and 5 extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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).
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
Complete walkthrough, full working code, and extension challenges.
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.
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.
Browser-based Python runtime via Pyodide. Run any Python 3 code without installation.
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.
14 runnable Python code snippets for common real-world tasks.