Python syllabus
About Python
Section titled “About Python”Python is a general-purpose programming language. The program you install from python.org, which reads and runs Python code, is called CPython. This course uses CPython 3.14.7.
Python is dynamically typed. A type belongs to each value, not to the name that refers to it, so one name can refer to a number now and to text later. Python’s official type-hint proposal states that the language will stay dynamically typed and that type hints will never be required.
The problem it solves. Python lets you write working programs with less code than lower-level languages. It groups statements by indentation instead of brackets, and it provides high-level data types, such as lists and dictionaries, that you would otherwise have to build yourself. Its creator, Guido van Rossum, took both ideas from an earlier teaching language called ABC.
What it is not designed for.
- Checking types itself. Type hints are information for tools and readers. Python does not check them when the code runs.
- Running untrusted code safely. The official security policy says that CPython does not support sandboxing, which means running untrusted code in a restricted, safe space.
- Running inside a web browser. Browsers natively run only JavaScript, so Python is used on the server side.
Who maintains it. The Python Software Foundation and the core development team maintain Python under the Python Software Foundation License, Version 2. A new feature release comes out every year. Bug-fix releases follow about every two months, and each version receives security fixes until five years after its release.
What carries over if Python fades. Python’s syntax carries over the least. What carries over is the set of questions every language answers in its own way: how names refer to values in memory, how errors travel through a program, how code is split into modules, how iteration works, and how a program does several things at once. This course asks each of those questions in general first, and then teaches Python’s answer, so that your next language is easier.
Who this syllabus is for and what you need first
Section titled “Who this syllabus is for and what you need first”This syllabus is for a complete beginner. It assumes no knowledge of Python or of any other programming language, and no experience with the terminal. Every term is explained where it is first used.
You need three things before you start:
- a computer running Windows, macOS or Linux, on which you are allowed to install programs;
- a way to reach the official documentation at docs.python.org, which the course links to throughout;
- time. The estimates below add up to about 114 hours. They are planning figures: a module is never shortened to meet its estimate, and every module can be paused at the end of any section.
The course follows one project from start to finish: a command-line expense tracker that you build, extend and keep.
What you will be able to do
Section titled “What you will be able to do”Each part of the course gives you one ability:
- Getting started. Install Python, run code in the interactive interpreter and from script files, and move around the file system from a terminal.
- Python fundamentals. Write short programs that read input, calculate with numbers and text, make decisions, repeat work and organise code into functions.
- Data structures. Store and process collections of data with lists, tuples, dictionaries and sets, and predict when a change through one name appears through another.
- Modules, files and exceptions. Split a program into modules and packages, read and write text, JSON and CSV files, and handle errors deliberately.
- Object-oriented programming. Model data and behaviour with classes, reuse code through inheritance and composition, and make objects work with Python’s built-in syntax.
- Intermediate Python. Use iterators, generators, decorators, context managers, functional tools and type hints, and recognise them in any library’s code.
- Concurrency. Run work concurrently with threads, processes and asyncio, and explain which one fits a task.
- The standard library. Use standard-library modules for dates, text patterns, command-line interfaces and logging, and learn an unfamiliar module from its documentation.
- Ecosystem and tooling. Work in a virtual environment, install third-party packages, and keep code consistently formatted.
- Testing and debugging. Find the cause of a bug methodically with a debugger, and prove code works with automated tests.
- Larger programs. Plan, structure, test and finish a multi-module program on your own.
By the end, without AI help and with only the official Python documentation open, you will be able to:
- build a complete command-line expense tracker from an empty folder: several files, functions and classes, JSON and CSV files, deliberate error handling, its own virtual environment and passing automated tests;
- read 50–100 lines of unfamiliar Python, explain every line, and predict what it prints before running it;
- take a broken program and its error report, and find and fix the cause within 30 minutes;
- open the first tutorial page of any widely used Python library, in web backend, data processing, AI or automation, and explain every Python language feature on it;
- learn a standard-library module you have never used from its documentation page, and use it correctly within 45 minutes.
The exact wording of this goal is under How this syllabus was built, at the end of the page.
Course outline
Section titled “Course outline”Each topic shows how deeply it is covered:
- In depth — you learn to use it yourself without the page open, and the module tests it.
- Overview — you learn what it is and when you would need it, and the module says where it is taught in depth.
- Reference — you learn what it is for, and the module links the exact place in the official documentation.
Part 1 — Getting started
Section titled “Part 1 — Getting started”Install Python, run code in the interactive interpreter and from script files, and move around the file system from a terminal.
- Module 1 · The command line (about 4 h 20 min) — Open a terminal, move between folders, run programs and read their exit status.
- The terminal and the shell
- Terminal, shell and prompt — In depth — the terminal only displays text; the shell reads a command, runs it and prints its output
- Commands, arguments and options — In depth — how the shell splits one typed line into a program name and the words passed to it
- Paths and the working directory
- The working directory — In depth — every command runs inside one folder, and relative paths start from that folder
- Absolute and relative paths — In depth — why the same file name can point to different files depending on where you are
- cd, ls and mkdir — In depth — the three navigation commands used in every later module, with their Windows equivalents
- Running programs
- Running a program from the terminal — In depth — how the shell finds a program through the PATH variable
- Exit status — In depth — 0 means success and any other number means failure; how to print the last one
- Environment variables
- Reading and setting environment variables — In depth — named settings every program inherits from the shell;
PATHis the one that decides which programs run
- Reading and setting environment variables — In depth — named settings every program inherits from the shell;
- The terminal and the shell
- Module 2 · Installing Python and an editor (about 1 h 55 min) — Install Python 3.14, confirm which version runs, and open a project in an editor.
- Python versions
- Choosing a Python version — In depth — why this course pins 3.14, and what the yearly release and five-year support cycle mean
- Installing on Windows, macOS and Linux
- Using Python on Windows — Overview — the python.org installer and the
pylauncher - Using Python on macOS — Overview — the python.org installer versus the Python some systems already have
- Using Python on Unix platforms — Overview — the distribution’s own Python, and why you should not modify it
- Checking the installation — In depth —
python --version, and what to do when the command is not found
- Using Python on Windows — Overview — the python.org installer and the
- Editors and IDEs
- Choosing an editor — Overview — what an editor adds over a plain text file, and the options the official docs list
- Visual Studio Code — In depth — opening a folder, the integrated terminal, and running the current file
- Pylance — Overview — the extension that marks errors as you type; AI completion is switched off for learning
- Python versions
- Module 3 · Using the Python interpreter (about 2 h 50 min) — Run Python code interactively and from files, pass arguments to a script, and ask Python itself for help.
- Invoking the interpreter
- Running a script file — In depth —
python file.pyruns the whole file from top to bottom - Argument passing — In depth — words after the file name arrive in
sys.argvas strings - Running a module with
-m— In depth —python -m venvandpython -m piprun a module found on the import path, not a file -cand standard input — Reference — running a one-line program or code piped into Python- Executable Python scripts — Overview — the
#!line that lets macOS and Linux run a script directly
- Running a script file — In depth —
- Interactive mode
- The interactive interpreter — In depth — the
>>>prompt echoes the value of each expression, whichprintis not needed for help()anddir()— In depth — asking Python what an object is and what it can do, instead of guessing- pydoc — Reference — the documentation tool behind
help() - Interactive input editing and history — Overview — history, tab completion and multi-line editing in the 3.14 shell
- Alternatives to the interactive interpreter — Overview — enhanced shells such as IPython and bpython, which the tutorial names
- Inspecting after a script with
-i— Overview — dropping into the shell when a script ends or crashes, also set byPYTHONINSPECT - quit and exit — Reference — the helpers the shell adds, and the Ctrl+D / Ctrl+Z shortcuts
- Interactive shell settings — Reference —
PYTHONSTARTUP,PYTHON_HISTORY,PYTHON_BASIC_REPLandPYTHON_COLORS
- The interactive interpreter — In depth — the
- The interpreter and its environment
- Source code encoding — In depth — source files are read as UTF-8, and the rare encoding declaration
- The customization modules — Overview —
siteruns at start-up and addssitecustomizeandusercustomize - Command-line options — Reference —
python --help,--help-all,--help-env,--help-xoptions,-X,-q,-u,-x,PYTHONUNBUFFERED
- Invoking the interpreter
Part 2 — Python fundamentals
Section titled “Part 2 — Python fundamentals”Write short programs that read input, calculate with numbers and text, make decisions, repeat work and organise code into functions.
- Module 4 · Basic syntax (about 4 h 20 min) — Write and run small programs, read the error report when one fails, and fix syntax errors on your own.
- Programming terminology
- Statements and expressions — In depth — a statement does something; an expression produces a value
- Literals — Overview — a literal writes a value directly in the code
- Lines and indentation
- Logical and physical lines — Overview — one statement can span several typed lines
- Line joining — In depth — continuing a statement inside brackets, and why the backslash form is avoided
- Indentation — In depth — leading spaces form a block;
IndentationErrorandTabErrorwhen they disagree - Tokens and whitespace — Reference — how source text is split into tokens, in the reference
- Comments
- Comments with # — In depth —
#text is ignored; comments say why, not what
- Comments with # — In depth —
- Names and keywords
- Identifiers — In depth — the rules for a valid name, including non-ASCII letters
- Keywords — In depth — the 35 reserved words that cannot be names
- Soft keywords — Overview —
match,case,_andtypeare reserved only in certain places - Reserved classes of identifiers — Overview — what
_name,__nameand__name__signal - The keyword module — Reference — checking from code whether a word is reserved
- Printing and reading input
print()— In depth — printing several values, and thesepandendargumentsinput()— In depth —input()always returns a string, whatever the user typed- EOFError — Overview — what
input()raises when the input stream ends
- Reading error messages
- SyntaxError — In depth — reading the caret, and why the reported spot may not be where the fix goes
- Reading a traceback — In depth — read from the bottom: error type, message, then the file, line and
~/^markers - NameError — In depth — a misspelled or undefined name, and the ‘Did you mean’ suggestion
- Programming terminology
- Module 5 · Variables and data types (about 5 h 40 min) — Store values in variables and choose and convert between numbers, booleans and None.
- Variables and assignment
- The assignment statement — In depth — a name is bound to an object; assignment never copies
- Objects, values and types — In depth — every object has an identity, a type and a value;
type()andid()show two of them - The standard type hierarchy — Reference — the reference’s map of every built-in type
- Augmented assignment — In depth —
+=and its relatives, and that they rebind the name - Dynamic typing — In depth — types belong to values, not to names, so a name can refer to any type
- Numbers
- int and float — In depth — whole numbers of any size and floating-point numbers
- Arithmetic operators — In depth —
+ - * / // % **, and why/always gives a float - Arithmetic conversions — In depth — mixing
intandfloatin one expression gives afloat - Numeric built-in functions — In depth —
abs(),round(),divmod()andpow() - Floating-point arithmetic: issues and limitations — In depth — why
0.1 + 0.2 != 0.3and how to compare floats safely - ZeroDivisionError — In depth — dividing by zero, and checking before dividing
- OverflowError — Overview — the rare case where a float result is too large
- Complex numbers — Overview —
3j,complex()andcmath, used in engineering maths - Additional methods on int and float — Reference —
bit_length(),is_integer()and other methods - Hashing of numeric types — Reference — why
1 == 1.0gives equal hashes - Integer string conversion length limitation — Reference — the 4300-digit limit and the options that change it
- The decimal module — In depth — exact decimal arithmetic for money, and creating a
Decimalfrom a string - The fractions module — Reference — exact rational numbers
- Booleans and None
- bool — In depth —
TrueandFalse, and that they behave as 1 and 0 in arithmetic - Truth value testing — In depth — which values count as false:
0, empty strings and collections,None - None — In depth — the single object that means ‘no value’
- Built-in constants — Overview —
True,False,None,NotImplemented,Ellipsisand__debug__
- bool — In depth —
- Type conversion
int(),float(),str()andbool()— In depth — each builds a new value of its type from another value, and fails loudly on bad input- ValueError and TypeError — In depth — a right-type-wrong-value error versus a wrong-type error
- Variables and assignment
- Module 6 · Strings (about 4 h 35 min) — Create, slice, search and format text, and print aligned, rounded output.
- String literals
- Single, double and triple quotes — In depth — choosing quotes, and multi-line strings
- Escape sequences — In depth —
\n,\t,\\and quotes inside strings - Raw strings — In depth — backslashes kept as typed, for regular expressions and Windows paths
- String prefixes — Reference — every combination of
r,b,fandt
- The str type
- Text sequence type str — In depth — a string is an immutable sequence of characters;
str()makes one len()— In depth — the number of items, for strings and every other collection- Indexing and slicing — In depth — positions start at 0, negative positions count from the end, and slices never raise
- Text sequence type str — In depth — a string is an immutable sequence of characters;
- String methods
- Common string methods — In depth —
split,join,strip,replace,lower,upper,startswith,find - The in operator,
isdigit()andisalpha()— In depth —in,isdigit()andisalpha()before converting input
- Common string methods — In depth —
- Formatted string literals
- f-strings — In depth — inserting values and expressions into text with
{} - Format specification mini-language — In depth — width, alignment, decimal places and thousands separators
- The
=specifier — In depth —f'{x=}'prints the expression and its value, for quick debugging
- f-strings — In depth — inserting values and expressions into text with
- Other ways to format strings
- The
str.format()method — Overview —'{}'.format(), found in older code;format()formats one value - printf-style string formatting — Overview —
%formatting, still used in logging calls - Template strings — Overview —
string.Templatefor templates written by users - t-strings — Overview — template string literals, new in 3.14, for safe processing of inserted values
- Manual string formatting — Overview —
rjust(),ljust()andcenter()pad text to a width
- The
- Unicode and character codes
ord()andchr()— In depth — characters are numbered code pointsrepr()andascii()— Overview — the developer-facing form of a value- Unicode HOWTO — Overview — what Unicode, code points and encodings are
- The unicodedata module — Reference — character names and categories
- String literals
- Module 7 · Operators and expressions (about 3 h) — Predict the result of comparison, boolean, membership and identity expressions before running them.
- Comparison operators
- Comparisons — In depth —
< <= > >= == !=, and chained comparisons such as0 < x < 10 - Value comparisons — In depth — what
==compares for numbers, strings and mixed types
- Comparisons — In depth —
- Boolean operators
- and, or and not — In depth — short-circuit evaluation, and that
and/orreturn one of their operands
- and, or and not — In depth — short-circuit evaluation, and that
- Membership and identity
- in and not in — In depth — membership tests on strings and collections
- is and is not — In depth —
iscompares identity, is used forNone, and gives aSyntaxWarningwith literals
- Conditional expressions
- x if condition else y — In depth — choosing between two values inside one expression
- Assignment expressions
- The walrus operator — Overview —
:=assigns inside an expression, mostly inwhileloops
- The walrus operator — Overview —
- Bitwise operators
&,|,^,~,<<and>>— Overview — they act on the bits of integers; you meet them in flag valuesbin(),hex()andoct()— Overview — writing integers in base 2, 16 and 8
- Operator precedence
- Precedence and parentheses — In depth — which operator applies first, and adding parentheses to make the order obvious
- Evaluation order — Overview — operands are evaluated from left to right
- Atoms and primaries — Reference — the grammar terms the reference uses for expressions
- Comparison operators
- Module 8 · Conditional statements: if, elif and else (about 2 h) — Make a program choose between several paths depending on its input.
- The if statement
- if — In depth — running a block only when a condition is true
- elif and else
- Choosing exactly one branch — In depth —
eliftests further conditions, andelseruns when none was true - Nested conditions — In depth — an
ifinside anotherif, and whenandis clearer
- Choosing exactly one branch — In depth —
- The pass statement
- pass — In depth — a statement that does nothing, for a block you must write but cannot fill yet
- The if statement
- Module 9 · Loops: for and while (about 2 h 40 min) — Repeat work with for and while loops, and stop a loop early or skip an item.
- The while statement
- while — In depth — repeating while a condition is true, and making sure the condition changes
- Infinite loops and KeyboardInterrupt — In depth — stopping a runaway program with Ctrl+C
- The for statement
- for — In depth — running a block once for each item of a sequence
- The
range()function — In depth — counting with start, stop and step; the stop value is excluded
- break and continue
- break — In depth — leaving a loop immediately
- continue — In depth — skipping to the next item
- else clauses on loops
- else on loops — Overview — the
elseblock runs only when the loop was not left bybreak
- else on loops — Overview — the
- The while statement
- Module 10 · Functions (about 5 h 10 min) — Define functions with parameters and return values, and predict which variable a name refers to.
- Defining functions
- def and calling a function — In depth — parameters, arguments and what happens during a call
- The return statement — In depth —
returnversusprint, and theNonereturned when there is noreturn - Documentation strings — In depth — the first string in a function documents it, and
help()shows it - Function objects — Overview — a function is an object that can be stored and passed; taught in full in Decorators
- Default argument values
- Optional parameters — In depth — a parameter with a default can be left out of the call
- The mutable default argument trap — In depth — a default is created once, when
defruns, so a list default is shared between calls
- Keyword arguments
- Passing arguments by name — In depth — the rules for mixing named and positional arguments in one call
- Special parameters
- Positional-only parameters — Overview — what
/in a signature means when you read library code - Keyword-only arguments — Overview — what
*in a signature means when you read library code
- Positional-only parameters — Overview — what
- Arbitrary argument lists
*argsand**kwargs— In depth — collecting any number of positional and keyword arguments- Unpacking argument lists — In depth —
f(*items)andf(**options)at the call site
- Lambda expressions
- lambda — In depth — a small unnamed function for one expression, mostly used as a
key
- lambda — In depth — a small unnamed function for one expression, mostly used as a
- Scopes and namespaces
- Local and global scope — In depth — names assigned in a function are local; Python looks names up local, enclosing, global, built-in
- UnboundLocalError — In depth — why assigning to a name anywhere in a function makes it local everywhere in that function
- The global statement — In depth — assigning to a module-level name, and why to avoid it
- The nonlocal statement — Overview — assigning to a name in the enclosing function; used again in Decorators
- The builtins namespace — Overview — where
printandlenlive, and why a variable calledlistbreakslist() globals(),locals()andvars()— Reference — reading namespaces as dictionaries
- Recursion
- Base case and recursive case — In depth — a function that calls itself must have a case that stops the calls
- RecursionError — In depth — the default limit of 1000 nested calls, and the repeated-line traceback
- Defining functions
Part 3 — Data structures
Section titled “Part 3 — Data structures”Store and process collections of data with lists, tuples, dictionaries and sets, and predict when a change through one name appears through another.
- Module 11 · Lists (about 3 h 50 min) — Build, change, sort and summarise lists of values.
- Creating and indexing lists
- Lists — In depth — an ordered, changeable sequence;
list()builds one - Common sequence operations — In depth — indexing, slicing,
len,in,+and*work on every sequence - IndexError — In depth — an index past the end, and the off-by-one mistakes that cause it
slice()— Reference — slice objects, used when writing custom containers
- Lists — In depth — an ordered, changeable sequence;
- List methods
- Mutable sequence operations — In depth —
append,extend,insert,pop,removeandclearchange the list itself - The del statement — In depth — removing an item or a slice by position
- Mutable sequence operations — In depth —
- Sorting
sort()andsorted()— In depth — sorting in place versus making a new list, and thekeyargumentreversed()— In depth — iterating backwards without copying
- Summarising a list
len(),sum(),min()andmax()— In depth — the four summaries used on every list of numbersall()andany()— In depth — checking whether every item, or at least one item, is true
- Using lists as stacks and queues
- Using lists as stacks — In depth —
appendandpopfrom the end - Using lists as queues — Overview — why removing from the front is slow, and
collections.deque
- Using lists as stacks — In depth —
- Creating and indexing lists
- Module 12 · Tuples and sequences (about 1 h 30 min) — Group values into tuples and unpack them into separate names.
- Tuples
- tuple — In depth — an immutable sequence; the commas make the tuple, not the parentheses
- Packing and unpacking
- Tuple packing and sequence unpacking — In depth —
a, b = b, aandfirst, *rest = items
- Tuple packing and sequence unpacking — In depth —
- Comparing sequences
- Item-by-item comparison — Overview — sequences compare their first items, then their second, until one differs
- Tuples
- Module 13 · Dictionaries (about 2 h 25 min) — Map keys to values, look them up safely and count or group data with the collections module.
- Creating and using dictionaries
- Mapping types — dict — In depth — keys map to values, and insertion order is kept
- KeyError and
get()— In depth — a missing key raises;get()returns a default instead - Dictionary view objects — In depth —
keys(),values()anditems()reflect later changes
- Hashable keys
hash()and hashability — In depth — why a list cannot be a dictionary key and a tuple can- Hash randomization — Reference —
PYTHONHASHSEED, and why string hashes differ between runs
- The collections module
- Counter, defaultdict, namedtuple and deque — In depth — the four containers that replace most hand-written counting and grouping code
- Creating and using dictionaries
- Module 14 · Sets (about 1 h 30 min) — Remove duplicates and compare collections with set operations.
- Set types
- Sets — In depth — an unordered collection of unique, hashable items with fast membership tests
- frozenset — Overview — an immutable set that can be a dictionary key
- Set operations
- Union, intersection and difference — In depth —
|,&,-and^, and their method forms
- Union, intersection and difference — In depth —
- Set types
- Module 15 · Object references and mutability (about 1 h 55 min) — Predict when changing an object through one name shows up through another, and copy data safely.
- Names and objects
- Aliasing — In depth — two names can refer to one object, and a change through one is visible through the other
- Mutable and immutable types — In depth — which built-in types can change in place, and why immutable ones cannot surprise you
- Copying objects
- Shallow and deep copy — In depth —
copy.copy,copy.deepcopy,list(x),x[:], and the[[0]*3]*3trap
- Shallow and deep copy — In depth —
- Passing objects to functions
- Call by object reference — In depth — a function can change a mutable argument but cannot rebind the caller’s name
- Memory management
- Garbage collection — Overview — reference counting frees most objects; the
gcmodule finds cycles - Weak references — Overview — references that do not keep an object alive, used for caches
- ReferenceError — Reference — using a weak reference after its object is gone
- Garbage collection — Overview — reference counting frees most objects; the
- Names and objects
- Module 16 · Comprehensions (about 1 h 45 min) — Build lists, sets and dictionaries from other collections in one readable expression.
- List comprehensions
- Writing a list comprehension — In depth —
[expr for x in items if cond]and the loop it replaces - Nested list comprehensions — In depth — reading two
forclauses in order, and when a loop is clearer
- Writing a list comprehension — In depth —
- Set and dictionary comprehensions
- Building sets and dictionaries in one expression — In depth — the same form with
{}, producing a set or a dictionary
- Building sets and dictionaries in one expression — In depth — the same form with
- List comprehensions
- Module 17 · Looping techniques (about 2 h 25 min) — Loop over indexes, pairs and dictionaries cleanly, and change a collection safely while processing it.
enumerate()andzip()enumerate()— In depth — getting the position and the item togetherzip()— In depth — walking several sequences in step, and what happens when their lengths differ
- Looping over dictionaries
items(),keys()andvalues()in loops — In depth —for key, value in d.items()walks both at once
- Modifying a collection while looping over it
- Changing a list while looping over it — In depth — the skipped-item bug and the two safe patterns
- RuntimeError: dictionary changed size during iteration — In depth — what the message means and how to loop over a copy
Part 4 — Modules, files and exceptions
Section titled “Part 4 — Modules, files and exceptions”Split a program into modules and packages, read and write text, JSON and CSV files, and handle errors deliberately.
- Module 18 · Modules and packages (about 3 h 30 min) — Split a program into modules and packages and control what Python finds when it imports.
- Modules
- Creating your own modules — In depth — a
.pyfile is a module, and importing it runs it once - The import statement — In depth —
import x,from x import yandas - Executing modules as scripts — In depth —
if __name__ == "__main__":separates running from importing - The module cache — Overview — why a second import does not run the file again:
sys.modules
- Creating your own modules — In depth — a
- The module search path
sys.path— In depth — the script’s folder,PYTHONPATHand the standard library, searched in order- ModuleNotFoundError and ImportError — In depth — a module that cannot be found versus a name missing inside a found module
- Shadowing a library module — In depth — a file named like a library module hides it; the ‘consider renaming’ hint
- Search-path options — Reference —
-E,-I,-P,-s,-Sand the related environment variables
- Compiled Python files
__pycache__and.pycfiles — Overview — cached bytecode, and why it is safe to delete- Bytecode options and tools — Reference —
-B,--check-hash-based-pycs,pycache_prefix,compileall,py_compile
- Packages
__init__.py— In depth — a folder with__init__.pyis a regular package that groups modules- Intra-package references — In depth — relative imports such as
from . import parsing - Importing
*from a package — Overview —__all__decides whatfrom package import *brings in - Submodules — Overview —
package.moduleand when a submodule is imported - Namespace packages — Overview — packages without
__init__.py - Packages in multiple directories — Reference — the
__path__attribute
- The import system
- importlib and the import machinery — Reference — finders, loaders, module specs, the meta path and import hooks
__import__()— Reference — the function behind theimportstatement- Tracing imports — Reference —
-v,-X importtimeand their environment variables - Future statements — Reference —
from __future__ import ...
- Modules
- Module 19 · Reading and writing files (about 3 h) — Read and write text files safely, choose the right encoding and handle missing files.
- Opening files
open()and file modes — In depth —r,w,a,x, and text versus binary mode- File objects — In depth — reading all at once, line by line, or by iterating; writing
- Closing files with with — In depth — why a file must be closed and how
withguarantees it; the statement is taught in full in Context managers
- Text encodings
- Specifying the encoding — In depth — the default encoding depends on the platform, so pass
encoding="utf-8" - UTF-8 mode — Overview —
-X utf8andPYTHONUTF8, and the 3.15 change to UTF-8 by default - EncodingWarning — Overview — finding calls that rely on the default with
-X warn_default_encoding - UnicodeDecodeError and UnicodeEncodeError — In depth — what each means and how to fix the encoding
- Standard stream encoding — Reference —
PYTHONIOENCODING - Codecs — Reference — the
codecsmodule and the list of standard encodings
- Specifying the encoding — In depth — the default encoding depends on the platform, so pass
- File-system errors
- OSError — In depth — the parent of every operating-system error
- FileNotFoundError, PermissionError and IsADirectoryError — In depth — the errors
open()raises and what each one tells you
- Binary files
- Bytes objects — Overview — binary mode reads
bytes, notstr, anddecode()converts - Bytearray and bytes operations — Reference — mutable bytes and the methods on binary data
- Binary sequence types and memoryview — Reference — views of binary data without copying
- The
-boption — Reference — warnings when bytes and text are compared
- Bytes objects — Overview — binary mode reads
- Opening files
- Module 20 · JSON and CSV files (about 1 h 45 min) — Load and save structured data as JSON and CSV.
- JSON
- The json module — In depth —
dump,dumps,loadandloads, and how JSON types map to Python types - JSONDecodeError — In depth — reading the line and column in the message to find the broken spot
- The json module — In depth —
- CSV
- The csv module — In depth —
reader,DictReader,DictWriter, and opening withnewline=''
- The csv module — In depth —
- Other file formats
- TOML with tomllib — Overview — reading TOML configuration such as
pyproject.toml - INI files with configparser — Reference — the older configuration format
- plistlib and netrc — Reference — two platform-specific formats
- TOML with tomllib — Overview — reading TOML configuration such as
- JSON
- Module 21 · Errors and exceptions (about 3 h 50 min) — Handle expected errors deliberately, raise your own, and let unexpected ones surface with a useful traceback.
- Exceptions
- How an exception travels up the call stack — In depth — an error raised while the program runs moves outward through each caller until something handles it
- Reading a traceback through several functions — In depth — each frame is one call, and the last frame is where it failed
- Handling exceptions
- try and except — In depth — catching one named exception type and nothing else
- else and finally — In depth — code that runs only on success, and code that always runs
- Overly broad except clauses — In depth — why
except Exception: passhides bugs and lets bad data through
- The exception hierarchy
- BaseException and Exception — In depth — which classes to catch, and why
KeyboardInterruptis not anException - LookupError and ArithmeticError — Overview — parent classes that group related errors
- AttributeError — In depth — asking an object for something it does not have, often
None - The full list of built-in exceptions — Reference — the rarer errors, including the connection and process errors
- BaseException and Exception — In depth — which classes to catch, and why
- Raising exceptions
- raise — In depth — signalling an error with a clear message
- Exception chaining — In depth —
raise ... from errkeeps the original cause visible
- User-defined exceptions
- Subclassing Exception — In depth — naming your program’s own errors so callers can catch exactly them
- Raising and handling multiple unrelated exceptions
- Exception groups and
except*— Overview — several errors raised together, as in concurrent code - Enriching exceptions with notes — Overview —
add_note()adds context to an error
- Exception groups and
- Warnings
- The warnings module — Overview — messages that do not stop the program;
DeprecationWarningis the one you will meet most - Python Development Mode — Overview —
-X devandPYTHONDEVMODEshow warnings and extra checks - Controlling warnings — Reference —
-WandPYTHONWARNINGS - Warning categories — Reference — the other warning classes
- The warnings module — Overview — messages that do not stop the program;
- EAFP and LBYL
- Try first or check first — Overview — easier to ask forgiveness than permission versus look before you leap, and when each is right
- Exceptions
- Module 22 · File and directory access (about 2 h 5 min) — Build file paths, list and search folders, and copy or move files from Python.
- pathlib
- Path objects — In depth — joining paths with
/, reading their parts, and checking whether they exist - Listing and searching folders — In depth —
iterdir(),glob()andrglob()
- Path objects — In depth — joining paths with
- The os module
os.getcwd(),os.environandos.listdir()— In depth — the working folder, the environment, and a folder’s contentsos.path— Overview — the older string-based path functions you will read in existing code
- File and directory operations
- shutil — In depth — copying, moving and deleting files and folders
- glob and fnmatch — Overview — shell-style wildcards outside
pathlib - Temporary files — Overview —
tempfilefor scratch files and folders - Other file and directory modules — Reference —
filecmp,statandlinecache
- pathlib
Part 5 — Object-oriented programming
Section titled “Part 5 — Object-oriented programming”Model data and behaviour with classes, reuse code through inheritance and composition, and make objects work with Python’s built-in syntax.
- Module 23 · Classes and objects (about 3 h 20 min) — Define classes with attributes and methods, and create and use instances of them.
- Class definition syntax
- Class definitions — In depth —
class, the class body and creating an instance
- Class definitions — In depth —
- Class objects and instance objects
- Instance objects and attributes — In depth — each instance has its own attributes, reached with a dot
__init__— In depth — the method that sets up a new instance
- Method objects
- Methods and self — In depth — a method is a function bound to an instance, which arrives as
self
- Methods and self — In depth — a method is a function bound to an instance, which arrives as
- Class and instance variables
- Shared class attributes — In depth — a class attribute is shared by every instance, which is a trap when it is mutable
- Encapsulation
- Protecting an object’s state — In depth — changing data only through methods keeps the object valid
property()— In depth — computed and validated attributes that look like plain attributes- Private variables — Overview — the
_nameconvention and__namemangling
- Class methods and static methods
- classmethod — In depth — alternative constructors such as
from_dict - staticmethod — Overview — a function kept in a class that needs neither the instance nor the class
- classmethod — In depth — alternative constructors such as
- Working with attributes by name
getattr(),setattr(),hasattr()anddelattr()— Reference — attribute access with the name in a string
- Special attributes
__dict__,__class__,__name__and__doc__— Overview — the attributes Python gives every class and instance
- Class definition syntax
- Module 24 · Inheritance (about 2 h 10 min) — Share behaviour between classes with inheritance, and choose composition when it fits better.
- Subclasses
- Overriding methods — In depth — a subclass reuses the parent’s methods and replaces the ones it overrides
super()— In depth — calling the parent’s version of a methodisinstance()andissubclass()— In depth — checking an object’s type the way inheritance intends- object — Overview — the class every class inherits from
- Multiple inheritance
- Mixins and multiple parents — Overview — a class that combines behaviour from several parent classes
- Method resolution order — Overview — the order Python searches parent classes
- Composition
- Has-a versus is-a — In depth — holding another object as an attribute instead of inheriting from it
- Abstract base classes
- abc.ABC and
@abstractmethod— Overview — declaring the methods a subclass must supply - NotImplementedError — Overview — raised by a method a subclass must supply
- The numbers ABCs — Reference — the numeric tower
- abc.ABC and
- Customizing class creation
- Metaclasses and class creation hooks — Overview — what a metaclass is and why application code rarely needs one
- Subclasses
- Module 25 · Special methods (about 2 h 45 min) — Make your objects print, compare, add and behave like containers by writing special methods.
- Special method names
- How syntax calls special methods — In depth —
len(x)callsx.__len__(), andx == ycallsx.__eq__(y) - Special method lookup — Overview — special methods are looked up on the class, not the instance
- How syntax calls special methods — In depth —
- Basic customization
__repr__and__str__— In depth — the developer form and the user form of an object__eq__and__hash__— In depth — why objects that compare equal must have equal hashes- Ordering and
__bool__— In depth —__lt__withfunctools.total_ordering, and truthiness
- Emulating numeric types
- Operator overloading — In depth —
__add__and friends, and returningNotImplemented
- Operator overloading — In depth —
- Emulating container types
- Container methods — In depth —
__len__,__getitem__,__iter__and__contains__
- Container methods — In depth —
- Emulating callable objects
__call__andcallable()— Overview — objects that can be called like functions
- Customizing attribute access
__getattr__,__slots__and descriptors — Overview — how attribute lookup works, and the Descriptor Guide behind properties and methods- Emulating generic types — Reference —
__class_getitem__
- Special method names
- Module 26 · Data classes (about 1 h 30 min) — Replace hand-written data-holding classes with dataclasses.
- The dataclass decorator
@dataclass— In depth — which special methods it generates for you
- Fields
- Fields and
default_factory— In depth — typed fields, defaults, and why a list default needsfield(default_factory=list)
- Fields and
- Frozen and ordered dataclasses
- frozen and order — Overview — immutable instances and generated ordering
- The dataclass decorator
- Module 27 · Enumerations (about 1 h 15 min) — Represent a fixed set of named values with enum.
- Enum
- Members, values and iteration — In depth — named constants, looping over them, and finding a member by its value
- Flag and IntFlag
- Flag — Overview — combinable options using bitwise operators
- Enum
- Module 28 · The match statement (about 1 h 45 min) — Choose between cases by matching the shape of data with match and case.
- Overview
- match and case — In depth — comparing one value against several patterns, top to bottom
- Patterns
- Literal, capture, sequence, mapping and class patterns — In depth — what each kind of pattern matches and what it binds
- Class patterns and
__match_args__— Overview — matching positional fields of your own classes
- Guards
case ... if condition— In depth — adding a condition that must also hold for the case to run
- Irrefutable case blocks
case _:— Overview — a case that matches anything, so it must come last
- Overview
Part 6 — Intermediate Python
Section titled “Part 6 — Intermediate Python”Use iterators, generators, decorators, context managers, functional tools and type hints, and recognise them in any library’s code.
- Module 29 · Iterators and generators (about 2 h 40 min) — Write generators that produce values lazily, and explain what a for loop does behind the scenes.
- Iterators
- Iterator types — In depth — an iterable produces an iterator; a
forloop callsiter()and thennext() - StopIteration — In depth — how an iterator signals that it is finished
- Exhausted iterators — In depth — why looping over the same iterator twice gives nothing the second time
- Iterator types — In depth — an iterable produces an iterator; a
- Generators
- yield — In depth — a function with
yieldpauses and resumes, producing one value at a time - Yield expressions — Overview —
send()andyield from - GeneratorExit — Reference — what a generator sees when it is closed
- yield — In depth — a function with
- Generator expressions
- Lazy comprehensions in parentheses — In depth —
(x for x in items)produces items one at a time instead of building a list
- Lazy comprehensions in parentheses — In depth —
- The itertools module
- itertools — In depth —
islice,chain,groupbyandbatched
- itertools — In depth —
- Iterators
- Module 30 · Decorators (about 2 h 40 min) — Pass functions as values, write closures, and write and read decorators.
- Functions as objects
- Higher-order functions — In depth — passing a function as an argument and returning one from a function
- Callable types — Overview — functions, methods and classes are all callable
- Closures
- Captured variables — In depth — an inner function keeps using names from the function that created it
- Late binding in closures — In depth — why lambdas made in a loop all see the last value, and the fix
- Writing decorators
- Decorators — In depth —
@decoabovedef fmeansf = deco(f) functools.wraps— In depth — keeping the decorated function’s name and docstring- Decorators with arguments — In depth — a function that returns a decorator
- Decorators — In depth —
- Functions as objects
- Module 31 · Context managers (about 1 h 45 min) — Use and write context managers that guarantee clean-up code runs.
- The with statement
- Setup, body and guaranteed clean-up — In depth — clean-up runs even when the block raises an error
- Writing context managers
__enter__and__exit__— In depth — the two methodswithcalls, and what__exit__receives on an errorcontextlib.contextmanager— In depth — writing a context manager as a generator with oneyield
- Clean-up at exit
- atexit — Reference — functions that run when the interpreter exits
- The with statement
- Module 32 · Functional programming (about 1 h 35 min) — Transform data with map, filter, functools and operator instead of hand-written loops.
- Programming paradigms
- Procedural, object-oriented and functional styles — Overview — how the three styles differ, and how Python mixes them
- Functional programming style — Overview — pure functions and avoiding changed state
- Built-in functional tools
map()andfilter()— In depth — applying a function to each item and keeping the items that pass a test
- The functools module
- functools — In depth —
reduce,partial,cacheandlru_cache
- functools — In depth —
- The operator module
- operator — Overview — operators as functions, such as
itemgetterfor sort keys
- operator — Overview — operators as functions, such as
- Programming paradigms
- Module 33 · Type hints (about 2 h 10 min) — Annotate code with type hints, check it with a type checker, and read the hints in library code.
- Function annotations
- Annotating parameters and return values — In depth —
def f(x: int) -> str:, and that Python does not check it - Annotated assignment — In depth —
x: int = 0, and that Python does not enforce it
- Annotating parameters and return values — In depth —
- The typing module
- Any, Callable, TypedDict and Protocol — In depth — the typing tools you meet most often in library code
- Generic alias and union types — In depth —
list[int],dict[str, float]andint | None
- Generics
- Generic functions and classes — Overview — type parameters such as
def first[T](items: list[T]) -> T - Type aliases and the type statement — Overview — naming a complex type
- Generic functions and classes — Overview — type parameters such as
- How annotations are evaluated
- Deferred evaluation of annotations — Overview — 3.14 evaluates annotations only when asked
- annotationlib — Reference — reading annotations at run time
- Type checkers
- mypy, Pyright and pyrefly — Overview — programs that check type hints without running the code
- Runtime validation
- Pydantic — Overview — why data from outside the program still needs checking at run time
- Function annotations
Part 7 — Concurrency
Section titled “Part 7 — Concurrency”Run work concurrently with threads, processes and asyncio, and explain which one fits a task.
- Module 34 · Threading and multiprocessing (about 2 h 30 min) — Run I/O-bound work in threads and CPU-bound work in processes, and explain what the global interpreter lock changes.
- Concurrency and parallelism
- I/O-bound versus CPU-bound work — In depth — overlapping waits versus computing at the same instant, and why the difference decides the tool
- Threads
- threading — In depth — starting threads and waiting for them
- Race conditions and locks — In depth — why shared data needs a
Lock _thread— Reference — the low-level threading module
- The global interpreter lock
- What the GIL allows and prevents — In depth — only one thread runs Python code at a time in the default build
- Free threading — Overview — the optional build without the lock, and the
-X gil/PYTHON_GILswitches
- Processes
- multiprocessing — Overview — separate processes for CPU-bound work
- subprocess — Overview — running another program and reading its output
concurrent.futures- ThreadPoolExecutor and ProcessPoolExecutor — In depth —
submit,mapandas_completed
- ThreadPoolExecutor and ProcessPoolExecutor — In depth —
- Queues and scheduling
- queue — Overview — thread-safe queues for passing work between threads
- sched — Reference — a simple event scheduler
- The runtime model
- Runtime components — Reference — the reference’s model of processes, interpreters and threads
- Concurrency and parallelism
- Module 35 · Asynchronous programming with asyncio (about 2 h 45 min) — Write async functions, run several of them concurrently, and avoid calls that block the event loop.
- Coroutines
- async def and await — In depth — defining and awaiting coroutines
- RuntimeWarning: coroutine was never awaited — In depth — the only sign that a coroutine never ran
- The event loop
- asyncio and the event loop — In depth — one thread switching between tasks at each
await;asyncio.run()
- asyncio and the event loop — In depth — one thread switching between tasks at each
- Tasks
create_task, gather and TaskGroup — In depth — running coroutines concurrently and collecting results- Keeping references to tasks — In depth — a task with no reference can disappear before it finishes
- Blocking calls
- Blocking calls in async code — In depth — why
time.sleep()stalls every task, andasyncio.to_thread()
- Blocking calls in async code — In depth — why
- Async iteration and context managers
- async for and async with — Overview — asynchronous iterators and context managers
- Context variables
- contextvars — Overview — values that follow each task
- Debug mode
- asyncio debug mode — Overview —
PYTHONASYNCIODEBUGreports slow and never-awaited coroutines
- asyncio debug mode — Overview —
- Coroutines
Part 8 — The standard library
Section titled “Part 8 — The standard library”Use standard-library modules for dates, text patterns, command-line interfaces and logging, and learn an unfamiliar module from its documentation.
- Module 36 · Dates and times (about 1 h 35 min) — Parse, compare, format and do arithmetic with dates and times.
- The datetime module
- date, datetime and timedelta — In depth — creating dates, subtracting them and adding durations
- ISO 8601 formatting and parsing — In depth —
isoformat(),fromisoformat()andstrftime()
- Time zones
- zoneinfo — Overview — aware versus naive datetimes, and IANA time zones
- The time and calendar modules
- time — Overview — timestamps and
time.sleep() - calendar — Reference — calendar calculations
- time — Overview — timestamps and
- The datetime module
- Module 37 · Regular expressions (about 1 h 45 min) — Search, validate and extract text with regular expressions.
- The re module
- re functions — In depth —
search,match,fullmatch,findallandsub
- re functions — In depth —
- Pattern syntax
- Character classes, quantifiers and anchors — In depth — the pattern parts that describe which characters match and how many
- Groups
- Capturing and named groups — In depth — pulling parts out of a match by position or by name
- Regular expressions versus string methods
- Choosing string methods for simple checks — Overview —
startswith,inandsplitare clearer than a pattern for simple cases
- Choosing string methods for simple checks — Overview —
- The re module
- Module 38 · Command-line interfaces: sys.argv and argparse (about 1 h 45 min) — Build a command-line interface with options and help text, and exit with the right status.
- The sys module
- sys — In depth —
sys.argv,sys.stdin,sys.stdoutandsys.stderr sys.exit()and SystemExit — In depth — ending a program with an exit status
- sys — In depth —
- argparse
- Arguments, options and subcommands — In depth — positional arguments, options, types, defaults, subcommands and generated help
- Other command-line libraries
- getopt, optparse, cmd, getpass, fileinput and shlex — Reference — older or specialised command-line modules you may read in existing code
- The sys module
- Module 39 · Logging (about 1 h 45 min) — Record what a program does at the right level, to the console or a file.
- Logging levels
- DEBUG, INFO, WARNING, ERROR and CRITICAL — In depth — choosing a level for each message, and why logging beats
print
- DEBUG, INFO, WARNING, ERROR and CRITICAL — In depth — choosing a level for each message, and why logging beats
- Configuring logging
- basicConfig and loggers — In depth — configuring once at start-up, and a logger per module
- Handlers and formatters
- Logging to a file with timestamps — In depth — a handler decides where records go; a formatter decides how they look
- Logging levels
- Module 40 · Brief tour of the standard library (about 2 h 15 min) — Find a standard-library module for a task and learn to use it from its documentation page alone.
- Reading the library reference
- How a library page is organised — In depth — synopsis, functions, classes, examples and the ‘Added in version’ notes
- Mathematics
- math — Overview — functions such as
sqrt,floorandisclose - random — In depth — random numbers, choices and shuffling, and seeding for repeatable tests
- statistics — Overview — mean, median and standard deviation
- math — Overview — functions such as
- Internet access
urllib.request— Overview — fetching a web page from Python- smtplib and poplib — Overview — sending and receiving email
- email — Overview — building and parsing email messages
- Internet protocols and data handling — Reference —
base64,binascii,mimetypes,quopri,mailbox,ftplib,imaplib,http,socketserver,ipaddress,uuid,webbrowser,wsgirefandhtml
- Data compression
- zlib, gzip, bz2 and lzma — Overview — compressing data and files
- zipfile and tarfile — Overview — reading and writing archives
compression.zstd— Reference — Zstandard, new in 3.14
- Performance measurement
- timeit — Overview — timing a small piece of code reliably
- profile, cProfile and pstats — Overview — finding where a program spends its time
- trace — Reference — tracing which lines run
- Batteries included
- sqlite3 — Overview — a database in a single file, with no server
- xml and xmlrpc — Overview — XML parsing and XML-RPC
- gettext and locale — Overview — translations and regional formatting
- Output formatting
- pprint — Overview — printing nested data readably
- textwrap — Overview — wrapping text to a width
- reprlib — Reference — shortened
repr()for large objects
- Working with binary data record layouts
- struct — Overview — packing numbers into bytes and back
- Tools for working with lists
- array, bisect and heapq — Overview — compact arrays, sorted insertion and priority queues
- Data persistence
- pickle — Overview — saving Python objects, and why never to load a pickle from an untrusted source
- shelve, dbm, copyreg and marshal — Reference — other persistence modules
- Cryptographic services
- secrets — Overview — secure random tokens and passwords
- hashlib and hmac — Reference — hashes and message authentication
- Text processing services
- difflib — Overview — comparing sequences and showing differences
- readline, rlcompleter and stringprep — Reference — line editing and string preparation
- Generic operating system and runtime services
- inspect — Overview — examining live objects, such as a function’s signature
- platform, errno, ctypes, types and sysconfig — Reference — system information, error codes, C libraries, type names and build settings
- graphlib — Reference — topological sorting
- Networking and interprocess communication
- socket, ssl, select, selectors, signal and mmap — Reference — the low-level networking and process-communication modules
- Multimedia services
- colorsys and wave — Reference — colour conversion and WAV files
- Security considerations
eval(),exec()andcompile()— Overview — running text as code, and why it must never receive untrusted input
- Reading the library reference
Part 9 — Ecosystem and tooling
Section titled “Part 9 — Ecosystem and tooling”Work in a virtual environment, install third-party packages, and keep code consistently formatted.
- Module 41 · Virtual environments and packages (about 2 h 30 min) — Create a virtual environment, install and pin third-party packages, and describe a project’s dependencies.
- Introduction
- Why virtual environments exist — In depth — each project needs its own set of packages and versions
- Creating virtual environments
- venv — In depth —
python -m venv .venv, activating it, and what activation changes
- venv — In depth —
- Managing packages with pip
- pip — In depth — installing, upgrading, removing and listing packages
- PyPI — In depth — the public package index, and checking a package before installing it
- Requirements files — In depth — pinning exact versions with
pip freezeand installing from the file - ensurepip — Reference — how pip is bundled with Python
- Installing Python Modules — Reference — the official installation guide
- Project configuration
pyproject.toml— Overview — the file most projects use to describe dependencies and tool settings- uv — Overview — a newer tool that combines environment and package management
- Introduction
- Module 42 · Code style and formatting (about 1 h 20 min) — Write code that follows PEP 8 and keep it formatted and linted automatically.
- PEP 8
- Naming, line length, whitespace and imports — In depth — the style rules most Python code follows
- The Zen of Python — Overview —
import thisand the principles behind Python’s style
- Formatters and linters
- Ruff — Overview — a linter and formatter run from the terminal or the editor
- Black — Overview — the formatter many projects standardise on
- tabnanny — Reference — detecting ambiguous indentation
- PEP 8
Part 10 — Testing and debugging
Section titled “Part 10 — Testing and debugging”Find the cause of a bug methodically with a debugger, and prove code works with automated tests.
- Module 43 · Debugging (about 2 h 20 min) — Find the cause of a bug methodically, using tracebacks, print statements and the debugger.
- Debugging strategy
- Reproduce, hypothesise, test, change one thing — In depth — a repeatable method that replaces guessing
- Print debugging
- Printing values with
f'{x=}'— In depth — a fast first check before the debugger, and removing the prints afterwards
- Printing values with
- The Python debugger
breakpoint()and pdb — In depth — pausing a program, stepping, and inspecting variables- Post-mortem debugging — In depth — opening the debugger at the point of a crash
- The debugger in Visual Studio Code — In depth — breakpoints, stepping and watching values in the editor
- Tracebacks in code
- The traceback module — Overview — printing and formatting tracebacks from your own code
- Traceback objects and frames — Reference — the internal objects behind a traceback
- Hiding location markers — Reference —
-X no_debug_rangesandPYTHONNODEBUGRANGES
- Crash and memory diagnostics
- faulthandler — Reference — tracebacks for hard crashes
- tracemalloc — Reference — finding where memory was allocated
- Debugging strategy
- Module 44 · Testing (about 1 h 50 min) — Write and run automated tests that check functions, including the errors they should raise.
- The assert statement
- assert and AssertionError — In depth — checking a condition, and the error raised when it is false
- Optimisation flags remove asserts — Overview —
-O,-OOandPYTHONOPTIMIZEturnassertoff
- unittest
- TestCase, assertion methods and assertRaises — In depth — writing test cases and running them from the terminal
- Test discovery — In depth — how
python -m unittestfinds test files unittest.mock— Overview — replacing a dependency during a test
- doctest
- Examples in docstrings as tests — Overview — examples in documentation that are run and checked
- pytest
- Plain assert with a third-party runner — Overview — the runner most library tutorials use, with plain
assertstatements
- Plain assert with a third-party runner — Overview — the runner most library tutorials use, with plain
- The assert statement
Part 11 — Larger programs
Section titled “Part 11 — Larger programs”Plan, structure, test and finish a multi-module program on your own.
- Module 45 · Developing a larger application (about 1 h 45 min) — Plan and build a complete multi-module program from an empty folder.
- Planning a program
- From description to modules and functions — In depth — deciding the pieces before writing code
- Separating concerns
- Separating input, logic and output — In depth — keeping file handling and printing out of the calculation code
- Documenting and testing the finished program
- README, error messages and a final test run — In depth — error messages, a README, and running the tests before calling it done
- Planning a program
Module summary
Section titled “Module summary”| # | Module | What you will learn | Estimated time | Needs first |
|---|---|---|---|---|
| 1 | The command line | Open a terminal, move between folders, run programs and read their exit status. | 4 h 20 min | Nothing |
| 2 | Installing Python and an editor | Install Python 3.14, confirm which version runs, and open a project in an editor. | 1 h 55 min | The command line |
| 3 | Using the Python interpreter | Run Python code interactively and from files, pass arguments to a script, and ask Python itself for help. | 2 h 50 min | Installing Python and an editor |
| 4 | Basic syntax | Write and run small programs, read the error report when one fails, and fix syntax errors on your own. | 4 h 20 min | Using the Python interpreter |
| 5 | Variables and data types | Store values in variables and choose and convert between numbers, booleans and None. | 5 h 40 min | Basic syntax |
| 6 | Strings | Create, slice, search and format text, and print aligned, rounded output. | 4 h 35 min | Variables and data types |
| 7 | Operators and expressions | Predict the result of comparison, boolean, membership and identity expressions before running them. | 3 h | Strings |
| 8 | Conditional statements: if, elif and else | Make a program choose between several paths depending on its input. | 2 h | Operators and expressions |
| 9 | Loops: for and while | Repeat work with for and while loops, and stop a loop early or skip an item. | 2 h 40 min | Conditional statements: if, elif and else |
| 10 | Functions | Define functions with parameters and return values, and predict which variable a name refers to. | 5 h 10 min | Loops: for and while |
| 11 | Lists | Build, change, sort and summarise lists of values. | 3 h 50 min | Functions |
| 12 | Tuples and sequences | Group values into tuples and unpack them into separate names. | 1 h 30 min | Lists |
| 13 | Dictionaries | Map keys to values, look them up safely and count or group data with the collections module. | 2 h 25 min | Tuples and sequences |
| 14 | Sets | Remove duplicates and compare collections with set operations. | 1 h 30 min | Dictionaries |
| 15 | Object references and mutability | Predict when changing an object through one name shows up through another, and copy data safely. | 1 h 55 min | Sets |
| 16 | Comprehensions | Build lists, sets and dictionaries from other collections in one readable expression. | 1 h 45 min | Sets |
| 17 | Looping techniques | Loop over indexes, pairs and dictionaries cleanly, and change a collection safely while processing it. | 2 h 25 min | Comprehensions, Dictionaries |
| 18 | Modules and packages | Split a program into modules and packages and control what Python finds when it imports. | 3 h 30 min | Functions |
| 19 | Reading and writing files | Read and write text files safely, choose the right encoding and handle missing files. | 3 h | Modules and packages, Lists |
| 20 | JSON and CSV files | Load and save structured data as JSON and CSV. | 1 h 45 min | Reading and writing files, Dictionaries |
| 21 | Errors and exceptions | Handle expected errors deliberately, raise your own, and let unexpected ones surface with a useful traceback. | 3 h 50 min | JSON and CSV files |
| 22 | File and directory access | Build file paths, list and search folders, and copy or move files from Python. | 2 h 5 min | Errors and exceptions |
| 23 | Classes and objects | Define classes with attributes and methods, and create and use instances of them. | 3 h 20 min | File and directory access |
| 24 | Inheritance | Share behaviour between classes with inheritance, and choose composition when it fits better. | 2 h 10 min | Classes and objects |
| 25 | Special methods | Make your objects print, compare, add and behave like containers by writing special methods. | 2 h 45 min | Inheritance |
| 26 | Data classes | Replace hand-written data-holding classes with dataclasses. | 1 h 30 min | Special methods |
| 27 | Enumerations | Represent a fixed set of named values with enum. | 1 h 15 min | Data classes |
| 28 | The match statement | Choose between cases by matching the shape of data with match and case. | 1 h 45 min | Enumerations |
| 29 | Iterators and generators | Write generators that produce values lazily, and explain what a for loop does behind the scenes. | 2 h 40 min | The match statement |
| 30 | Decorators | Pass functions as values, write closures, and write and read decorators. | 2 h 40 min | Iterators and generators |
| 31 | Context managers | Use and write context managers that guarantee clean-up code runs. | 1 h 45 min | Decorators |
| 32 | Functional programming | Transform data with map, filter, functools and operator instead of hand-written loops. | 1 h 35 min | Context managers |
| 33 | Type hints | Annotate code with type hints, check it with a type checker, and read the hints in library code. | 2 h 10 min | Functional programming |
| 34 | Threading and multiprocessing | Run I/O-bound work in threads and CPU-bound work in processes, and explain what the global interpreter lock changes. | 2 h 30 min | Type hints |
| 35 | Asynchronous programming with asyncio | Write async functions, run several of them concurrently, and avoid calls that block the event loop. | 2 h 45 min | Threading and multiprocessing |
| 36 | Dates and times | Parse, compare, format and do arithmetic with dates and times. | 1 h 35 min | Asynchronous programming with asyncio |
| 37 | Regular expressions | Search, validate and extract text with regular expressions. | 1 h 45 min | Dates and times |
| 38 | Command-line interfaces: sys.argv and argparse | Build a command-line interface with options and help text, and exit with the right status. | 1 h 45 min | Regular expressions |
| 39 | Logging | Record what a program does at the right level, to the console or a file. | 1 h 45 min | Command-line interfaces: sys.argv and argparse |
| 40 | Brief tour of the standard library | Find a standard-library module for a task and learn to use it from its documentation page alone. | 2 h 15 min | Logging |
| 41 | Virtual environments and packages | Create a virtual environment, install and pin third-party packages, and describe a project’s dependencies. | 2 h 30 min | Brief tour of the standard library |
| 42 | Code style and formatting | Write code that follows PEP 8 and keep it formatted and linted automatically. | 1 h 20 min | Virtual environments and packages |
| 43 | Debugging | Find the cause of a bug methodically, using tracebacks, print statements and the debugger. | 2 h 20 min | Code style and formatting |
| 44 | Testing | Write and run automated tests that check functions, including the errors they should raise. | 1 h 50 min | Debugging |
| 45 | Developing a larger application | Plan and build a complete multi-module program from an empty folder. | 1 h 45 min | Testing |
What this syllabus does not cover
Section titled “What this syllabus does not cover”Everything below was considered and left out on purpose. The first entry is taught by the official tutorial, so it is listed first and carries the strongest reason.
| Not covered | Why it is left out | When it becomes worth learning |
|---|---|---|
winreg |
Windows registry access. The tutorial mentions it once, but no program in the course’s final goal reads or writes the registry. | You write a Windows-specific tool that stores settings in the registry. |
| Using Python on Android, Using Python on iOS | Running Python on phones is outside every area named in the course’s final goal. | You build a mobile app that embeds Python. |
| Configure Python | Building Python from source is for people who work on Python itself; you install a released version. | You need a Python build with options the installers do not offer. |
| Distributing Python Modules | Publishing packages for other people to install is outside the agreed scope of this course. | You want to publish a library to PyPI. |
| Poetry, PDM, Pipenv, virtualenv, pyenv, conda | These six tools manage environments, packages or Python versions. The course already covers those jobs with venv, pip and the python.org installer, and names uv as the newer alternative. | A team you join uses one of them. |
| YAPF, Sphinx, tox | One roadmap’s picks for formatting, multi-version testing and documentation sites. None is needed for the course’s final goal. | You maintain a library that needs a documentation site or tests across several Python versions. |
| Arrays and linked lists, Hash maps, Heaps, stacks and queues, Binary search trees, Sorting algorithms | Algorithms and data structures as a subject are outside the agreed scope of this course; the course teaches only the built-in structures and their costs. | You prepare for technical interviews or study the dsa-and-problem-solving entity. |
| Common packages and modules | Third-party libraries are separate packages after this one. | You start the entity for a specific library. |
| Django, Flask, FastAPI, Pyramid, Sanic, Tornado, AIOHTTP, gevent, Plotly Dash | Web frameworks are separate entities; this package teaches only the Python they are written in. | You start the Django, FastAPI or Flask entity. |
| Pygame | Game development is not an area in the course’s final goal. | You want to build a game. |
tkinter, turtle, turtledemo, idlelib |
Desktop GUI and teaching-graphics modules; none of your target areas uses a Tk interface. | You need a desktop window for a tool. |
msvcrt, winsound |
Windows-only helper modules with no role in portable programs. | You write Windows-specific tools. |
fcntl, grp, posix, pty, pwd, resource, syslog, termios, tty |
Unix-only low-level system interfaces; the portable modules taught in the course cover everything your programs need. | You write system-administration tools for Linux. |
ast, dis, symtable, token, tokenize, pyclbr, pickletools |
Tools for analysing Python source and bytecode, used by people who build linters and compilers. | You write a code-analysis tool or study how the interpreter works. |
code, codeop, bdb |
Building your own interactive interpreter or debugger is for tool authors. | You build an interactive shell or a debugger. |
curses |
Full-screen terminal user interfaces are not needed for a command-line tracker. | You build a text-based full-screen application. |
zipapp |
Packaging a program as a zip application is part of distribution, which is outside the agreed scope of this course. | You need to ship a single-file Python program. |
antigravity, genericpath, nt, ntpath, nturl2path, opcode, posixpath, pydoc_data, pyexpat, sre_compile, sre_constants, sre_parse |
Internal or joke modules with no documentation page; nothing in them is meant for application code. | Never, unless you work on the interpreter. |
-d, PYTHONDEBUG |
Parser debugging output is for developers of the Python interpreter. | You work on CPython itself. |
-X context_aware_warnings, PYTHON_CONTEXT_AWARE_WARNINGS, -X thread_inherit_context, PYTHON_THREAD_INHERIT_CONTEXT |
Thread-safety switches for warnings and context variables matter only in free-threaded programs, which the course names but does not teach. | You write free-threaded code. |
-X cpu_count, PYTHON_CPU_COUNT |
Overriding the reported CPU count is for container and benchmarking setups. | You tune a program’s parallelism inside containers. |
-X disable-remote-debug, PYTHON_DISABLE_REMOTE_DEBUG, Remote debugging attachment protocol |
Remote debugging attaches a debugger to a running process; the course teaches local debugging, which is enough for the course’s final goal. | You debug long-running services in production. |
-X frozen_modules, PYTHON_FROZEN_MODULES |
Frozen standard-library modules are a start-up optimisation you never need to change. | You investigate interpreter start-up time. |
-X perf, -X perf_jit, PYTHON_PERF_JIT_SUPPORT, PYTHONPERFSUPPORT, Python support for the Linux perf profiler |
Linux perf-profiler integration is performance engineering, outside the agreed scope of this course. | You profile CPU-heavy code at the system level. |
-X showrefcount, PYTHONMALLOC, PYTHONMALLOCSTATS, PYTHONDUMPREFS, PYTHONDUMPREFSFILE |
Reference-count and memory-allocator diagnostics are for interpreter and C-extension developers. | You debug a C extension. |
-X tlbc, PYTHON_TLBC, -X presite, PYTHON_PRESITE |
Build-specific switches that exist only on free-threaded or debug builds of Python. | You run a free-threaded or debug build. |
PYTHONCASEOK, PYTHONEXECUTABLE, PYTHONLEGACYWINDOWSFSENCODING, PYTHONLEGACYWINDOWSSTDIO, PYTHONCOERCECLOCALE |
Legacy compatibility switches for old Windows, macOS and locale behaviour. | You maintain code that depends on legacy platform behaviour. |
PYTHON_JIT |
The experimental JIT compiler. An independent benchmark in the research found no meaningful gain from it in 3.14, and it changes every release. | The JIT becomes the default and you need to understand its effect on performance. |
| C API Extension Support for Free Threading, Porting Extension Modules to Python 3, Isolating Extension Modules, Argument Clinic, Debugging C API extensions and CPython Internals with GDB, Instrumenting CPython with DTrace and SystemTap | C-extension and interpreter-internals guides; writing C code for Python is outside the agreed scope of this course. | You write or maintain a C extension. |
| How to port Python 2 Code to Python 3 | Porting Python 2 code; Python 2 reached end of life in 2020. | You inherit a Python 2 codebase. |
| Code Objects, Internal Objects | Code objects and the other internal object types matter only to tools that inspect or generate bytecode. | You build a tool that works with compiled code. |
How this syllabus was built
Section titled “How this syllabus was built”Show the sources, the decisions and the arithmetic behind this syllabus
The standard curricula it was built from. All five were read on 2026-09-21.
- The Python Tutorial (official)
- Python 3.14 documentation contents (official)
- Python Developer roadmap (roadmap.sh)
- Python Programming MOOC 2026 (University of Helsinki)
- Exercism Python track
Where the order differs from the official tutorial, and why.
- The command line and installing Python come first. The tutorial assumes both; this course teaches them from zero.
- Operators get their own module before conditional statements. The tutorial spreads them over several chapters; the roadmap and the courses give them their own section.
- Scope is taught inside the Functions module, because the first scope error appears as soon as you write functions. The tutorial places it in its chapter on classes.
- Recursion is added to the Functions module. The tutorial does not teach it; the Helsinki course, Exercism and the roadmap do.
- Object references and mutability move into the data structures part, because sharing one list between two names causes bugs from the moment you use lists. The tutorial explains this in its chapter on classes.
- The match statement moves from the tutorial’s fourth chapter to after the object-oriented part, because its patterns match lists, dictionaries and objects of your own classes.
- JSON and CSV files, and file and directory access, get their own modules. Every standard course treats file handling, data formats and the file system as separate subjects.
- Subjects the tutorial never teaches are added because another curriculum or the final goal needs them: decorators, writing context managers, functional programming, type hints, threading and multiprocessing, asyncio, debugging and code style.
Where the sources disagreed. The tutorial teaches comprehensions early and the Helsinki course teaches them late; this syllabus follows the tutorial. The roadmap’s own order could not be read, because its chart is drawn from data that is not published. Where the sources disagreed, the official tutorial’s order was followed except for the changes listed above.
The alignment check. Every chapter of the official tutorial maps to at least one module, except chapter 1, whose content is the About Python section above, and chapter 13, which lists further reading and has nothing to teach. Every topic on the roadmap maps to a module, except the algorithms, framework and alternative-tool topics listed under What this syllabus does not cover. Parts 1–12 of the Helsinki course map to modules; its game-programming parts 13–14 are left out. All 67 Exercism concepts map to modules.
The inventory arithmetic. The research listed every documented feature of Python 3.14.7, every topic in the five curricula, and four topics the course scope requires (the terminal). That gave 757 topics. Of these, 646 are covered by this syllabus and 111 are listed as not covered: 646 + 111 = 757. Of the 253 topics taught by the official tutorial or by at least two sources, 252 are covered and one is left out, the Windows registry module.
How the time estimates were computed. Each module’s estimate adds up a 15-minute first attempt; reading at 130 words a minute (900 words for each in-depth topic, 250 for each overview, 70 for each reference); one code example to read and one to type and run for each in-depth topic; diagrams; practice failures at 6 minutes each; the checkpoint; and 75 seconds for each quiz question. Everything that runs code then gets 25% extra for things going wrong. These are estimates for planning. Record your real times for the first modules, and the later estimates will be corrected from them.
The level arc. You start at level 0, knowing nothing, and finish at level 3, able to find and fix what is wrong in Python code. Most modules take you to level 2, writing the code yourself from a blank page. Three modules, Object references and mutability, Errors and exceptions and Debugging, take you to level 3.
The final goal, word for word as it was agreed on 2026-09-21:
Without AI, with only docs.python.org open:
- Write. From an empty folder, build a command-line expense tracker he keeps: multiple files, functions and classes, reads and writes JSON and CSV files, deliberate error handling, its own virtual environment, passing automated tests.
- Read. Given 50–100 lines of unfamiliar Python, explain each line and predict the output before running it.
- Debug. Given a broken program and its traceback, find and fix the cause within 30 minutes.
- Read any Python library’s code. For four widely used libraries picked at random — one each from web backend, data processing, AI/machine learning, automation/scripting — open the first official tutorial page and explain every Python LANGUAGE feature on it without knowing the library.
- Learn on your own. Given a standard-library module he has never used, read its official documentation and use it correctly in a small program within 45 minutes.