Learn Python: Free Python Tutorial in 134 Lessons
Learn Python free: 134 lessons in 20 modules, from first programs to interview questions, with exercises judged on CPython 3.11 and a certificate.
- Language: Python
- Runtime: CPython 3.11
- Modules: 20
- Lessons: 134
- Reading time: about 34 hours
- Cost: Free on every plan, with a certificate
The language of data, scripting and the fastest interview rounds — the object model, comprehensions and generators, classes and the data model, exceptions, the standard library, typing, concurrency and performance — with exercises judged on a real CPython 3.11.
Syllabus
Module 1: Python and the interpreter
What CPython is and how it runs a file, the REPL, scripts and -m, the anatomy of a program, the console I/O patterns every exercise uses, and how to read a syntax error and a traceback.
- What Python is, and why it looks the way it does 12 min
- Running Python — the REPL, scripts, modules and the judge 12 min
- Anatomy of a Python program 13 min
- Console input and output — the patterns every exercise uses 14 min
- Errors and tracebacks — reading what the interpreter tells you 13 min
- Checkpoint — Python and the interpreter (checkpoint) 22 min
Module 2: Values, types and operators
Arbitrary-precision integers and floor division, floating point and the rules for comparing and printing it, truthiness and what and/or return, names bound to objects, explicit conversions and their errors, and operator precedence with the bitwise idioms.
- Numbers — int, float and the arithmetic that surprises 13 min
- Floating point — why 0.1 + 0.2 is not 0.3, and what to do about it 14 min
- Booleans, truthiness, None, and is versus == 13 min
- Names, binding and mutability — there are no boxes 14 min
- Conversions — between text, numbers and containers 12 min
- Operators and precedence 13 min
- Checkpoint — Values, types and operators (checkpoint) 25 min
Module 3: Control flow
if/elif/else and guard clauses, while with break, continue and else, for over any iterable with range, enumerate and zip, structural pattern matching with match, and the loop patterns interviews are built from.
Module 4: Functions
def and return, the full signature with defaults, *args, **kwargs and keyword-only parameters, LEGB scope with closures and late binding, recursion with memoisation, lambdas and the key-function idiom, and the type hints and docstrings that publish a function's contract.
- Defining functions — def, return and functions as values 12 min
- Parameters and arguments — positional, keyword, defaults, *args and **kwargs 15 min
- Scope and closures — LEGB, global, nonlocal and late binding 15 min
- Recursion — base cases, the call stack and memoisation 14 min
- Lambdas and higher-order functions 13 min
- Type hints and docstrings — the contract a function publishes 12 min
- Checkpoint — Functions (checkpoint) 25 min
Module 5: Strings and text
Strings as immutable sequences, slicing and the method set, f-strings and the format-spec mini-language, code points versus bytes with the digit tests, the parsing shapes for every input format, and regular expressions with groups and substitution.
- String basics — an immutable sequence of characters 12 min
- Slicing and the string methods 14 min
- Formatting — f-strings and the format-spec mini-language 14 min
- Characters, code points, bytes and Unicode 13 min
- Parsing input — from lines and tokens to values 14 min
- Regular expressions — the re module 15 min
- Checkpoint — Strings and text (checkpoint) 25 min
Module 6: Lists, tuples and sequences
Lists and their method costs, aliasing and copying, comprehensions in every form, sorting with keys, stability and bisect, tuples with unpacking and namedtuple, grids with neighbours and transposes, and the sequence tools with deque and the sequence protocol.
- Lists — the mutable sequence 14 min
- Comprehensions — building collections from expressions 13 min
- Sorting — sort, sorted, keys, stability and bisect 13 min
- Tuples, unpacking and named tuples 13 min
- Grids and nested lists 14 min
- The sequence tools — enumerate, zip, reversed, any, all, deque and the protocol 13 min
- Checkpoint — Lists, tuples and sequences (checkpoint) 25 min
Module 7: Dictionaries and sets
Dictionaries with get, setdefault, views and merging, counting and grouping with Counter and defaultdict, sets and their algebra, the hashing contract that decides what can be a key, nested data and JSON, and the complexity table with heapq.
- Dictionaries — the mapping at the centre of Python 14 min
- Counting and grouping — Counter, defaultdict and the accumulation idioms 13 min
- Sets — membership, deduplication and set algebra 13 min
- Hashing and keys — what makes an object usable in a dict or set 13 min
- Nested data and JSON 14 min
- Choosing a collection — the complexity table and heapq 13 min
- Checkpoint — Dictionaries and sets (checkpoint) 25 min
Module 8: Classes and objects
The class statement with __init__ and self, instance versus class attributes, the dunder methods that make a class behave like a built-in, @property and __slots__, class methods as alternative constructors, dataclasses and their options, and the design discipline of invariants and small interfaces.
- Defining classes — __init__, self, attributes and methods 14 min
- Dunder methods — making a class behave like a built-in 15 min
- Properties and encapsulation — the underscore, @property and __slots__ 13 min
- Class methods and static methods 12 min
- Dataclasses — classes that are mostly data 14 min
- Designing a class — invariants, interfaces and a worked example 14 min
- Checkpoint — Classes and objects (checkpoint) 25 min
Module 9: Inheritance, protocols and duck typing
Subclassing with super() and attribute lookup, duck typing with EAFP, abstract base classes and collections.abc, multiple inheritance with the MRO and mixins, typing.Protocol for structural typing, and composition over inheritance with Liskov, delegation and UserDict.
- Inheritance basics — subclasses, super() and attribute lookup 14 min
- Polymorphism and duck typing — EAFP, hasattr and programming to behaviour 13 min
- Abstract base classes — abc and collections.abc 14 min
- Multiple inheritance and the MRO — mixins and cooperative super() 14 min
- Protocols and structural typing — typing.Protocol 13 min
- Composition over inheritance — Liskov, delegation and wrapping built-ins 14 min
- Checkpoint — Inheritance, protocols and duck typing (checkpoint) 25 min
Module 10: Errors and exceptions
The try statement with else and finally, the hierarchy and matching, raise and chaining, custom exception classes, EAFP with suppress and sentinels, context managers as classes and generators, exception groups with except* and add_note, and assertions versus boundary validation.
- Exceptions — try, except, else, finally, raise 14 min
- Custom exceptions — a hierarchy for your own errors 13 min
- EAFP and exception-driven flow — suppress, retries, return versus raise 13 min
- Context managers — with, __enter__/__exit__ and contextlib 14 min
- Exception groups, notes and the traceback module 13 min
- Assertions and defensive code — validate at the boundary, assert the invariant 13 min
- Checkpoint — Errors and exceptions (checkpoint) 25 min
Module 11: Iterators, generators and itertools
The iteration protocol with iter, next and StopIteration, generators with yield and yield from, generator expressions and the short-circuit consumers, the itertools toolkit, functools and operator, and lazy pipelines of generator stages.
- The iteration protocol — iter, next and StopIteration 13 min
- Generators — functions that yield 14 min
- Generator expressions — lazy comprehensions 12 min
- itertools — the iterator toolkit 15 min
- functools and operator — the function toolkit 13 min
- Lazy pipelines — a worked log-processing example 14 min
- Checkpoint — Iterators, generators and itertools (checkpoint) 25 min
Module 12: Modules, packages and imports
What import does and the sys.modules cache, from-imports copying bindings, packages with __init__.py and relative imports, the standard-library map, virtual environments with pip and pyproject.toml, and command-line scripts with argparse, streams and exit codes.
- Modules and imports — files, namespaces and sys.modules 14 min
- Packages — directories, __init__.py, relative imports and project layout 14 min
- The standard library map — where to look before you write it 14 min
- Virtual environments and packaging — venv, pip and pyproject.toml 13 min
- Scripts and the command line — argv, argparse, exit codes and streams 14 min
- Checkpoint — Modules, packages and imports (checkpoint) 22 min
Module 13: The standard library in depth
math, statistics, Fraction, Decimal and seeded random; datetime arithmetic, parsing and time zones with zoneinfo; deque, Counter, OrderedDict, ChainMap and namedtuple in depth; textwrap, difflib, Template and the deeper re; and enums with auto, IntEnum, StrEnum and Flag.
- math, statistics, fractions, decimal and random 14 min
- Dates and times — datetime, timedelta and zoneinfo 14 min
- collections in depth — deque, Counter, OrderedDict, ChainMap and the User classes 13 min
- Text-processing tools — textwrap, difflib, string.Template and re in depth 14 min
- Enums — Enum, IntEnum, StrEnum, Flag and auto 13 min
- Checkpoint — The standard library in depth (checkpoint) 22 min
Module 14: Files and data formats
open with modes, encodings and with; pathlib for building, querying and listing paths; CSV with DictReader/DictWriter; JSON with custom encoders and dataclass round trips; bytes with struct, byte order, base64 and hashlib; and sqlite3 with parameters, transactions and aggregation.
- Reading and writing files — open, modes, encoding and with 13 min
- pathlib — paths as objects 13 min
- CSV — reader, writer, DictReader and the quoting rules 13 min
- JSON in depth — custom encoders, decoders, dataclasses and config files 13 min
- Bytes and binary data — struct, int.to_bytes, base64 and hashlib 13 min
- sqlite3 — a SQL database in the standard library 14 min
- Checkpoint — Files and data formats (checkpoint) 25 min
Module 15: Type hints and code quality
The hint vocabulary from generics and unions to TypeVar, Generic, Literal and TypedDict; what a type checker verifies and how narrowing works; PEP 8 layout, naming and docstrings with ruff and black; logging with levels, loggers, handlers and formats; and the idioms that make code Pythonic.
- Type hints in depth — generics, unions, Callable, TypeVar and Protocol 15 min
- Static analysis with mypy — narrowing, strictness and the run-time view of hints 13 min
- Code style and PEP 8 — layout, naming, imports, docstrings and the tools that enforce them 13 min
- logging — levels, loggers, handlers and formats 14 min
- Writing idiomatic Python — the idioms, the anti-patterns and a refactoring 14 min
- Checkpoint — Type hints and code quality (checkpoint) 22 min
Module 16: Decorators, descriptors and the data model
Decorators as functions wrapping functions with wraps, arguments and stacking; closures with cells, late binding and factories; the descriptor protocol behind properties and methods; the attribute hooks and reflection; classes as objects with type, __new__ and __init_subclass__; and the rest of the data model through a Vector.
- Decorators — functions that wrap functions 15 min
- Closures and late binding — cells, factories and stateful callables 13 min
- Descriptors — how properties, methods and validated attributes work 14 min
- Attribute access — __getattr__, __getattribute__, __setattr__, __dict__ and __slots__ 13 min
- Classes as objects — type, __new__, __init_subclass__ and metaclasses in outline 14 min
- The data model — the rest of the dunders, and a Vector that uses them 14 min
- Checkpoint — Decorators, descriptors and the data model (checkpoint) 25 min
Module 17: Concurrency — threads, processes and asyncio
The GIL and the CPU-bound/I/O-bound decision; threads with Lock, Queue and Event and the race you must see once; concurrent.futures executors with ordered map; multiprocessing with pickling and the main guard; asyncio from coroutines and gather to TaskGroup, semaphores and queues; and the determinism rule for every concurrent program.
- The GIL and the three models — threads, processes, asyncio 14 min
- Threads — Thread, Lock, Event, Queue and the race you must see once 15 min
- concurrent.futures — executors, futures, map and as_completed 13 min
- multiprocessing — Process, Pool, pickling, queues and shared state 13 min
- asyncio basics — coroutines, await, tasks and gather 15 min
- asyncio patterns — TaskGroup, queues, semaphores, async iteration and bridging 14 min
- Checkpoint — Concurrency (checkpoint) 25 min
Module 18: Testing and debugging
The testing mindset and designing for testability; unittest with its assertion family, fixtures, subTest and in-process runs; pytest's fixtures and parametrize and the mechanisms behind them; test doubles with Mock, side_effect and patch; and debugging by reading tracebacks, logging, pdb and the reproduce–minimise–bisect method.
- The testing mindset — what to test, how to arrange it, and designing for testability 13 min
- unittest — TestCase, assertions, fixtures, subTest and running suites 15 min
- pytest in outline — plain asserts, fixtures, parametrize and the command line 13 min
- Mocking and test doubles — Mock, patch, side_effect and where to patch 15 min
- Debugging — reading tracebacks, logging, pdb and the method 15 min
- Checkpoint — Testing and debugging (checkpoint) 25 min
Module 19: Memory, performance and the interpreter
The object model with reference counting and the cycle collector; the cost model of the built-in operations; bytecode, code objects and the 3.11 specialising interpreter; measuring with timeit, cProfile and tracemalloc; numeric performance with array, bytes and NumPy; and the checklist for writing fast Python.
- The object model — objects, references, reference counting and the cycle collector 15 min
- The cost model — what the built-in operations really cost 15 min
- Bytecode and the interpreter — code objects, dis, name lookup and the 3.11 specialiser 15 min
- Measuring — timeit, perf_counter, cProfile, tracemalloc and benchmarking hygiene 14 min
- Numeric performance — boxed numbers, array, bytes and NumPy vectorisation 14 min
- Writing fast Python — the checklist, from algorithm to micro-optimisation 14 min
- Checkpoint — Memory, performance and the interpreter (checkpoint) 25 min
Module 20: Interview idioms
The round and the file template with fast I/O, the idiom sheet of shapes and their Python, the twelve pitfalls interviewers watch for, a hash map, dynamic array, LRU cache and heap by hand, clean solutions under pressure, and the Python theory drill.
- The interview template — the round, the file, fast I/O and what is actually judged 14 min
- The idiom sheet — the shapes interview problems take and the Python for each 16 min
- Pitfalls that fail interviews — the twelve Python mistakes interviewers watch for 15 min
- Implement the built-in — a hash map, a dynamic array, an LRU cache and a heap by hand 16 min
- Writing clean solutions — structure, names, edges first and the code you can read aloud 13 min
- The Python theory drill — thirty questions, thirty answers 25 min
- Final checkpoint — Interview idioms (checkpoint) 30 min