Python

Python from Basics to Advanced

Learn the whole core of Python, topic by topic, from the first print to decorators, classes, the standard library and concurrency.

21 chapters 149 lessons
Start the course →

Course map

21 chapters in order. Start at the first, or jump to the one you need.

  1. Chapter 1 Python Getting Started Install Python, run your first program, and learn to read error messages. 4 lessons
  2. Chapter 2 Python Variables and Data Types Store values in variables and understand types, input, identity and copying. 7 lessons
  3. Chapter 3 Python Numbers and Math Integers, floats, precision, decimals, the math module and bitwise tools. 8 lessons
  4. Chapter 4 Python Strings Work with text: slicing, methods, f-strings, formatting, Unicode and bytes. 8 lessons
  5. Chapter 5 Python Conditions Make decisions with comparisons, if, match and logical operators. 6 lessons
  6. Chapter 6 Python Loops Repeat work with while and for, and learn the common loop patterns. 7 lessons
  7. Chapter 7 Python Lists Create, change, slice, sort and copy lists, and see how they work inside. 7 lessons
  8. Chapter 8 Python Tuples Fixed sequences, unpacking, swapping and named tuples. 4 lessons
  9. Chapter 9 Python Dictionaries Store key-value data: methods, nesting, ordering, grouping and hashing. 7 lessons
  10. Chapter 10 Python Sets Unique values, set operations, and when a set is the right choice. 4 lessons
  11. Chapter 11 Python Functions From first def to arguments, scope, recursion, closures and decorators. 11 lessons
  12. Chapter 12 Python Comprehensions, Iterators and Generators Build collections in one line and process data lazily with iterators and yield. 7 lessons
  13. Chapter 13 Python Classes and Objects Object-oriented Python: classes, inheritance, special methods and dataclasses. 14 lessons
  14. Chapter 14 Python Errors and Exceptions Handle errors with try, raise your own, and manage resources with with. 7 lessons
  15. Chapter 15 Python Files, Paths, CSV and JSON Read and write files, work with paths and folders, and handle CSV and JSON. 8 lessons
  16. Chapter 16 Python Modules, Packages and Environments Import, write and organise code, and manage packages with venv and pip. 6 lessons
  17. Chapter 17 Python Standard Library Tour the modules you will use most: dates, collections, re, logging and more. 11 lessons
  18. Chapter 18 Python Testing and Debugging Find bugs with print and pdb, write tests with unittest and pytest, and time code. 6 lessons
  19. Chapter 19 Python Type Hints and Code Quality Type hints, PEP 8, documentation and project layout. 5 lessons
  20. Chapter 20 Python Concurrency Threads, processes, concurrent.futures and asyncio, and how to choose. 6 lessons
  21. Chapter 21 Python Projects Put it all together in complete programs, then plan what to learn next. 6 lessons

1. Python Getting Started

  1. Python Getting Started Reading What Python is, how to run code on your own computer, and how to write and run a program that prints a message. Level: basic.
  2. Python Print, Strings and Comments Reading Printing several values, working with text, special characters, f-strings and writing comments to explain your code. Level: basic.
  3. Python Errors and How to Read Them Reading Why errors are normal, the three kinds you will meet first, and a method for reading an error message and fixing the problem. Level: basic.
  4. Python Scripts, the Shell and Editors Reading The different ways to run Python code (a file, the interactive prompt, one command), how to leave the prompt, and how to choose an editor. Level: basic.

2. Python Variables and Data Types

  1. Python Variables Reading How to store values in variables, how to name them well, and how to change, swap and reuse them. Level: basic.
  2. Python Data Types Reading What a data type is, the main built-in types (int, float, str, bool, None and the collections), how to check a type with type() and isinstance(), and why mixing types causes errors. Level: basic.
  3. Python Booleans and None Reading The two boolean values True and False, how comparisons produce them, how booleans behave like numbers, a first look at truthiness, and None, the value that means "nothing here". Level: basic.
  4. Python Type Conversion Reading How to convert values between int, float, str and bool, what happens to decimals and bad text, the automatic conversions Python does for you, and converting text in other number bases. Level: basic.
  5. Python User Input Reading How input() works, why it always returns text, converting the answer to a number, reading several values from one line, cleaning the text with strip() and lower(), and what goes wrong with bad input. Level: basic.
  6. Python Mutable vs Immutable Types Reading Which Python values can be changed in place and which cannot, how += behaves differently for each, what id() and is tell you, and why you test for equality with == but for None with is. Level: intermediate.
  7. Python References and Copying Reading Why assigning one name to another does not copy a list or dictionary, the three common ways to make a copy, the difference between shallow and deep copies, the [[0] * 2] * 3 trap, and how functions share mutable values. Level: advanced.

3. Python Numbers and Math

  1. Python Numbers Reading The number types int and float, how to write numbers (underscores, scientific notation), how large an int can be, the limits of float including inf and nan, and which type each operation returns. Level: basic.
  2. Python Operators Reading The arithmetic operators (+ - * / // % **), how floor division and the remainder behave with negative numbers, the order Python calculates in, augmented assignment such as +=, and division by zero. Level: basic.
  3. Python Number Functions Reading The built-in functions for numbers: abs, round (and why round(2.5) is 2), divmod, pow with a modulus, and min, max and sum over several values or a list. Level: basic.
  4. Python Float Precision Reading Why 0.1 + 0.2 is not exactly 0.3, how floats are stored, the traps this creates (equality, int(), money), and the safe habits: round for display, math.isclose to compare, whole numbers or decimal for money. Level: intermediate.
  5. Python Decimal and Fractions Reading Exact number types from the standard library: the decimal module for money and exact decimal arithmetic (creating, rounding with quantize, precision) and the fractions module for exact ratios. Level: intermediate.
  6. Python math Module Reading How to import and use the math module: constants (pi, e, inf, nan), roots and powers, floor, ceil and trunc, logs and trigonometry (radians), factorials and combinations, gcd and lcm, distance and isclose. Level: intermediate.
  7. Python Bitwise Operators and Number Bases Reading Binary, octal and hexadecimal numbers, writing and converting between bases with bin, oct, hex and int, the bitwise operators (& | ^ ~ << >>), practical bit tricks such as flags, and the order bitwise operators run in. Level: advanced.
  8. Python Complex Numbers Reading What complex numbers are, how to write them with j, their real and imaginary parts, arithmetic, abs and conjugate, why they cannot be compared with <, the cmath module, and a worked example solving a quadratic equation with no real roots. Level: advanced.

4. Python Strings

  1. Python Strings Reading What a string is, the ways to write one (single, double and triple quotes), escape sequences and raw strings, length, joining and repeating, comparing and ordering text, the in test, and the errors you meet first. Level: basic.
  2. Python String Slicing Reading How to get single characters with an index (counting from 0 or from the end), how to cut out pieces with slices [start:stop:step], how to reverse a string, what happens when a slice goes out of range, and why you cannot change a character in place. Level: basic.
  3. Python String Methods Reading The everyday string methods: changing case (upper, lower, title, casefold), removing spaces with strip, replace, startswith and endswith, the is-tests (isdigit, isalpha and others), padding with zfill and ljust, chaining methods, and the title() trap. Level: basic.
  4. Python Searching, Splitting and Joining Strings Reading How to find text with find and index, count matches, break a string into pieces with split, splitlines and partition, join pieces back with join, remove prefixes and suffixes, and translate characters. Level: basic.
  5. Python f-Strings Reading How to put values and calculations inside text with f-strings, a quick look at number formatting (:.2f and alignment), the = debugging shortcut, literal braces, quotes inside f-strings, the !r conversion, and multi-line f-strings. Level: basic.
  6. Python String Formatting Reading The format mini-language in full: fill and alignment, width, signs, grouping, precision, number types (decimal, binary, hex, scientific, percent), nested fields, dates, and the older format() method and % operator. Level: intermediate.
  7. Python String Immutability and Building Strings Reading Why strings cannot change, how to change a character through a list, why repeated += in a loop can be slow, how to build long text with join, StringIO and string.Template, and everyday patterns for filtering and transforming characters. Level: intermediate.
  8. Python Unicode, Encodings and Bytes Reading How Python represents text with Unicode code points, why len() can surprise you, normalisation, the difference between str and bytes, encoding and decoding with UTF-8, the common encoding errors and mojibake, and the rules that keep text safe. Level: advanced.

5. Python Conditions

  1. Python Comparison Operators Reading The six comparison operators (==, !=, <, >, <=, >=), what they return, how Python compares numbers, text, lists and tuples, what happens when the types do not fit, and the care needed with floats and NaN. Level: basic.
  2. Python If, Elif and Else Reading How to make a program choose with if, elif and else: the colon and indentation rules, the order of an elif chain, nested conditions, empty blocks with pass, using truthiness, and the errors you meet first. Level: basic.
  3. Python Logical Operators and Truthiness Reading How and, or and not combine conditions, their truth tables and order, the fact that and/or return one of their operands, the full list of false values, the classic mistake of writing n == 1 or 2, De Morgan's laws, and any() and all(). Level: basic.
  4. Python Conditional Expressions Reading The one-line choice value_if_true if condition else value_if_false: how it works, where it fits (f-strings, comprehensions, arguments), why only one branch runs, how it differs from or-defaults, and when a plain if statement is clearer. Level: intermediate.
  5. Python match Statement Reading Structural pattern matching with match and case (Python 3.10 and later): literals and the wildcard, OR patterns, capturing values, matching lists, dictionaries and objects, guards, and the pitfall of bare names. Level: intermediate.
  6. Python Chained Comparisons, Short-circuiting and the Walrus Operator Reading Chained comparisons such as 10 < x < 20 and their traps, how and/or stop early (short-circuiting) and how to use that to guard against errors, and the walrus operator := that assigns inside an expression. Level: advanced.

6. Python Loops

  1. Python While Loops Reading How a while loop repeats code as long as a condition is true: the three parts of a loop (start, test, update), counting and totalling, loops that run zero times, reading input until it is valid, and the infinite loop. Level: basic.
  2. Python For Loops and range() Reading How a for loop goes through the items of a string, list, tuple or dictionary, how range() produces number sequences, how the loop variable behaves, and the trap of changing a list while looping over it. Level: basic.
  3. Python Break, Continue and Loop Else Reading How break leaves a loop early, how continue skips to the next pass, what the else clause on a loop really means (it runs when the loop was not stopped by break), and how to leave several loops at once. Level: basic.
  4. Python Nested Loops Reading How a loop inside a loop works (the inner loop runs completely for every pass of the outer one), tables and patterns, going through rows and columns of a grid, all pairs and combinations, counting the passes, and the tool itertools.product. Level: intermediate.
  5. Python Loop Patterns Reading The patterns that most loops are built from: counting, accumulating, tracking the biggest or smallest, searching, building new lists, counting by category with a dictionary, finding unique items and grouping, and the built-in shortcuts for each. Level: intermediate.
  6. Python enumerate, zip, reversed and sorted Reading The four built-in helpers for loops: enumerate for positions, zip for walking several collections together (and unzipping), reversed for going backwards, and sorted for going in order, with the key and reverse options and the traps of one-time iterators. Level: intermediate.
  7. Python Loop Design and Infinite Loops Reading How to choose between for and while, what makes a loop stop (termination), the usual causes of infinite loops including a float trap, off-by-one errors, loops that retry with a limit, early exit, doing less work inside loops, testing edge cases and tracing a loop by hand. Level: intermediate.

7. Python Lists

  1. Python Lists Reading What a list is, how to create one, how to read items by index (forwards and backwards), length and membership, joining and repeating lists, comparing, unpacking, and how lists differ from strings and tuples. Level: basic.
  2. Python List Add and Remove Items Reading How to change a list in place: assigning to an index, append, extend, insert, remove, pop, del and clear, the difference between append and extend, why these methods return None, and how to remove every occurrence of a value. Level: basic.
  3. Python List Slicing Reading How to take pieces of a list with [start:stop:step] (a new list each time), common cuts such as first n, last n and reversing, how to replace, insert and delete whole pieces by assigning to a slice, and rotating and chunking lists. Level: basic.
  4. Python Searching and Sorting Lists Reading How to search a list with in, index and count, how to sort it in place with sort() or into a new list with sorted(), sorting with key and reverse (including records and ties), min and max with a key, the median, and fast searching in a sorted list with bisect. Level: basic.
  5. Python Copying and Nested Lists Reading How to make list copies that behave, why a shallow copy shares inner lists, how to build grids correctly (and the [[0] * 3] * 2 trap), reading and changing rows and columns, transposing, flattening, jagged lists and a tic-tac-toe board. Level: intermediate.
  6. Python Lists as Stacks and Queues Reading Using a list as a stack (last in, first out) with append and pop, why a list is a poor queue (first in, first out), how collections.deque fixes that, deques with a maximum length, rotating, and examples such as undo, bracket matching and a breadth-first search. Level: intermediate.
  7. Python List Internals Reading How a list is really stored (a row of references that grows in jumps), what is fast and what is slow (index, append, in, insert), a first look at big-O thinking, why lists hold references, the sorting algorithm, and when to choose a set, a deque, a tuple or an array instead. Level: advanced.

8. Python Tuples

  1. Python Tuples Reading What a tuple is, how to create one (including the one-item comma trap), indexing and slicing, why tuples cannot be changed, count and index, joining and comparing, tuples that hold lists, and when to choose a tuple rather than a list. Level: basic.
  2. Python Tuple Unpacking Reading How unpacking assigns the items of any sequence to several names at once, the rule that the counts must match, swapping and multiple assignment, unpacking in loops and function results, nested unpacking, ignoring values with an underscore, and the errors you may meet. Level: basic.
  3. Python Extended Unpacking and Swapping Reading How a starred name collects the extra items when unpacking (first, *rest = ...), the rules for the star, using the star in the other direction to spread collections into lists, tuples, dictionaries and function calls, and swap and rotate patterns with unpacking. Level: intermediate.
  4. Python Named Tuples Reading How namedtuple and typing.NamedTuple give the fields of a tuple readable names, how a named tuple still behaves like a tuple, replacing and converting fields, default values, the class syntax with types and methods, and how named tuples compare with dictionaries and dataclasses. Level: intermediate.

9. Python Dictionaries

  1. Python Dictionaries Reading What a dictionary is (keys mapped to values), the ways to create one, reading values with [] and get, adding, changing and deleting items, the KeyError, the rules for keys and values, and truthiness and equality. Level: basic.
  2. Python Dictionary Methods Reading The dictionary methods and what they return: keys, values and items as live views, get, setdefault, update in its different forms, pop, popitem, clear, copy, the merge operators | and |=, and the error for changing a dictionary while looping over it. Level: basic.
  3. Python Looping Through Dictionaries Reading How to loop over the keys, values or pairs of a dictionary, in sorted order, how to change values while looping, and how to build new dictionaries with loops and dictionary comprehensions (filtering, transforming, inverting, counting and grouping). Level: basic.
  4. Python Nested Dictionaries and JSON Reading How to work with dictionaries that contain dictionaries and lists, reading deep values safely, changing them, looping through records, building nested data with setdefault, flattening, and converting to and from JSON text with the json module, including what JSON cannot hold. Level: intermediate.
  5. Python Dictionary Ordering, Merging and Copying Reading How a dictionary remembers insertion order (and how updates, deletions and re-insertion change it), why equality ignores order, several ways to merge dictionaries (including a deep merge and ChainMap), and alias, shallow copy and deep copy. Level: intermediate.
  6. Python Sorting and Grouping Dictionaries Reading How to sort dictionary keys, values and pairs (with ties), how to find the top items, how to group records with setdefault, defaultdict and itertools.groupby, how to count with Counter, and how to compute totals and averages per group. Level: intermediate.
  7. Python Hashing and Dictionary Keys Reading How a dictionary finds a value fast using hash numbers, what hashable means and which types qualify, why mutable keys are not allowed, how equal values share a hash, string hash randomisation, making your own classes hashable, and the oddities of floats such as nan. Level: advanced.

10. Python Sets

  1. Python Sets Reading What a set is (an unordered collection of unique, hashable items), how to create one, why {} is not an empty set, adding and removing items (add, update, remove, discard, pop), membership tests, removing duplicates, set comprehensions, and the errors you may meet. Level: basic.
  2. Python Set Operations Reading The mathematical operations on sets: union, intersection, difference and symmetric difference, as operators and as methods, subset and superset tests, isdisjoint, the in-place versions, working with many sets at once, and the difference between operators and methods. Level: intermediate.
  3. Python Sets in Practice Reading When a set is the right tool: fast membership tests, distinct counts, duplicate checks, filtering, comparing collections (added, removed, kept), validating fields and permissions, similarity, tracking visited items, and when not to use a set. Level: intermediate.
  4. Python frozenset Reading What a frozenset is (an immutable, hashable set), how it differs from a set, which operations work and what type they return, using frozensets as dictionary keys and as items of other sets, sets of sets, and practical uses such as undirected edges, grouping and constants. Level: advanced.

11. Python Functions

  1. Python Functions Reading What a function is and why we write them, how to define one with def and call it, the difference between printing and returning a value, what a function gives back when it has no return, returning several values, early return, functions calling functions, and the common errors. Level: basic.
  2. Python Function Arguments and Return Values Reading How arguments are matched to parameters by position, the errors for wrong counts, what a function can do with the objects it receives (changing a list versus rebinding a name), changing the input versus returning a new value, and passing functions as arguments. Level: basic.
  3. Python Default and Keyword Arguments Reading How to give parameters default values, how to pass arguments by name in any order, the rules and errors when mixing positional and keyword arguments, defaults that are worked out once, the None pattern, and keyword-only and positional-only parameters. Level: basic.
  4. Python *args and **kwargs Reading How a function can accept any number of positional arguments (*args, a tuple) and keyword arguments (**kwargs, a dictionary), the order of parameters, unpacking into a call, forwarding arguments to another function, and common patterns. Level: intermediate.
  5. Python Scope and the LEGB Rule Reading Where a name can be seen: local, enclosing, global and built-in scope (LEGB), why assigning inside a function creates a new local name, the UnboundLocalError, the global and nonlocal statements, shadowing built-ins, and why loops and ifs do not make new scopes. Level: intermediate.
  6. Python Recursion Reading How a function can call itself: base case and recursive case, the call stack and the recursion limit, classic examples (factorial, Fibonacci, power, reversing, flattening, trees, towers of Hanoi, permutations), memoisation with lru_cache, and when a loop is the better choice. Level: intermediate.
  7. Python Lambda and Functions as Values Reading Functions are objects you can store, pass and return; lambda expressions for tiny functions; map, filter and reduce; the operator module and functools.partial; dispatch tables; composing functions; and the late-binding trap with lambdas created in a loop. Level: intermediate.
  8. Python Docstrings, Annotations and Function Design Reading How to document a function with a docstring and read it with help(), how type annotations describe parameters and results (but are not enforced), runnable examples with doctest, and habits for well-designed functions: one job, clear names, few parameters, no hidden effects. Level: intermediate.
  9. Python Mutable Defaults and Function Traps Reading The famous bug of a mutable default argument (one list or dictionary shared by every call), why it happens and the None fix, when a shared default is useful, and other traps: returning internal state, missing returns, empty input, silent keyword typos. Level: intermediate.
  10. Python Closures Reading How an inner function remembers variables of the function that made it, function factories, counters and accumulators with nonlocal, private state without a class, how to inspect a closure, closures versus classes, the loop trap once more, and examples such as memoize and once. Level: advanced.
  11. Python Decorators Reading What a decorator is (a function that wraps another function), the @ syntax, wrappers that accept any arguments, keeping the original name and docstring with functools.wraps, decorators with arguments, stacking, and practical decorators: logging, timing, retry, registry and caching. Level: advanced.

12. Python Comprehensions, Iterators and Generators

  1. Python List Comprehensions Reading How to build a new list in one expression with [expression for item in iterable], turning a loop into a comprehension, using strings, ranges, zip and enumerate, nested for clauses and nested comprehensions, variable scope, speed, and when a plain loop is more readable. Level: intermediate.
  2. Python Conditions in Comprehensions Reading The two places a condition can go in a comprehension, the filter at the end (if) and the choice inside the expression (if ... else), combining conditions, filtering records and messy data, the walrus operator to avoid repeating work, and the syntax mistakes to avoid. Level: intermediate.
  3. Python Dictionary and Set Comprehensions Reading How to build dictionaries with {key: value for ...} and sets with {item for ...}: transforming, filtering, renaming and inverting dictionaries, lookup tables from records, nested dictionaries, normalising with sets, key collisions, and why there is no tuple comprehension. Level: intermediate.
  4. Python Iterators and Iterables Reading The difference between an iterable and an iterator, how iter() and next() work, what a for loop really does, StopIteration, why iterators are used up, writing your own iterator class, restartable iterables, infinite iterators with islice, and handy idioms. Level: intermediate.
  5. Python Generators and yield Reading How a function with yield becomes a generator that produces values one at a time and pauses between them, lazy evaluation, infinite generators, return and yield from, saving memory, practical generators (chunks, windows, files), and sending values in with send(). Level: advanced.
  6. Python Generator Expressions Reading Generator expressions: comprehensions in round brackets that produce values lazily, feeding sum, max, any and all directly, early stopping, a trap about when each part is evaluated, chaining them into pipelines, the bracket rule, and when a list is better. Level: advanced.
  7. Python Lazy Pipelines and Memory Reading How to chain generators into a lazy pipeline that processes data one item at a time, seeing laziness and early stopping at work, the itertools toolbox (islice, takewhile, chain, accumulate, pairwise, batched), measuring memory with tracemalloc, and pitfalls. Level: advanced.

13. Python Classes and Objects

  1. Python Classes and Objects Reading What a class and an object are, how to define a class with class and __init__, creating instances, what self means, attributes that belong to each object, methods that act on them, how objects differ from each other, and the first errors. Level: intermediate.
  2. Python Attributes and Methods Reading How an object stores its data as attributes (in __dict__), reading and changing them with getattr, setattr and hasattr, bound methods, methods calling methods, returning self to chain calls, the mutable default trap in __init__, and objects that hold other objects. Level: intermediate.
  3. Python Class Attributes, Class Methods and Static Methods Reading Data shared by all objects of a class (class attributes) and how lookup works, the += trap, counting instances, class methods with cls (alternative constructors that work with subclasses), static methods for helpers, and how to choose between the three kinds of method. Level: intermediate.
  4. Python Encapsulation and Properties Reading Why objects protect their data, Python's conventions for internal names (single and double underscore, name mangling), read-only, validated and computed properties with @property, setters and deleters, cached properties, and protecting collections by returning copies. Level: intermediate.
  5. Python Inheritance Reading How a class can inherit attributes and methods from a parent class, defining subclasses, overriding methods, calling the parent with super(), the is-a test, isinstance and issubclass, subclassing list and dict, overriding class attributes, and when not to use inheritance. Level: intermediate.
  6. Python Polymorphism and super() Reading How different objects respond to the same method call (polymorphism), duck typing without inheritance, asking permission or forgiveness, polymorphism in built-ins and operators, how super() builds chains, keeping signatures compatible, and a payment example. Level: intermediate.
  7. Python Special Methods Reading What special (dunder) methods are, __str__ versus __repr__ and how to write both, making objects work with len, indexing, in, for, bool and calling, formatting and conversion, __getattr__, context managers, and a Playlist class that behaves like a collection. Level: advanced.
  8. Python Operator Overloading and Comparison Reading How to make your own objects work with +, -, *, ==, < and sum by defining special methods, returning NotImplemented, reflected operators like __radd__, the link between __eq__ and __hash__, ordering with __lt__ and total_ordering, in-place operators, and a Vector and Money example. Level: advanced.
  9. Python Composition or Inheritance? Reading The difference between is-a and has-a, building objects from other objects (composition) and delegating work to them, why a Stack that wraps a list is safer than one that inherits from it, dependency injection for testing, swappable strategies, and guidelines for choosing. Level: advanced.
  10. Python Abstract Base Classes Reading How abc.ABC and @abstractmethod force subclasses to implement required methods (the error appears at creation), abstract properties, the template-method pattern, the classes in collections.abc, register and __subclasshook__, and when to use them. Level: advanced.
  11. Python Dataclasses Reading How @dataclass writes __init__, __repr__ and __eq__ for you, default values, default_factory for lists, frozen and ordered dataclasses, __post_init__, field options, asdict and replace, inheritance, slots and kw_only, and when a dataclass is better than a plain class. Level: intermediate.
  12. Python Enums Reading How to use enum.Enum for fixed sets of named choices, members with name and value, lookup by value or name, iteration, comparison rules, IntEnum, auto(), Flag for combined options, methods and extra data on members, unique, and match statements. Level: intermediate.
  13. Python Multiple Inheritance and MRO Reading How a class can inherit from several parents, the diamond problem, how Python orders the search with the method resolution order (MRO) and C3 rule, how super() follows the MRO, cooperative __init__ with keyword arguments, mixins, and the errors and traps to avoid. Level: advanced.
  14. Python __slots__ and Descriptors Reading How __slots__ removes the per-object dictionary to save memory and block stray attributes, and how descriptors (__get__, __set__, __set_name__) power property, methods and reusable validated fields, with data and non-data descriptors, cached_property, and a Student example. Level: advanced.

14. Python Errors and Exceptions

  1. Python try and except Reading What exceptions are, how try and except catch an error so the program can carry on, catching specific types, several except blocks, grouping types, using the error object, how errors travel up through function calls, why bare except is dangerous, and a retry loop for user input. Level: basic.
  2. Python Exception Types and Tracebacks Reading How to read a traceback from the bottom up, what the most common exceptions mean (ValueError, TypeError, KeyError, IndexError, AttributeError, NameError, FileNotFoundError and more), the exception family tree, syntax errors versus run-time errors, and the traceback module. Level: basic.
  3. Python try else and finally Reading What the else and finally clauses of a try statement do, the order they run in, why else keeps the try block small, how finally always runs for cleanup even with return, break or an uncaught error, the return-in-finally trap, and a retry pattern. Level: intermediate.
  4. Python raise and Custom Exceptions Reading How to signal an error with raise, which built-in type to choose, re-raising with a bare raise, writing your own exception classes with extra data, building a hierarchy with one base class so callers can catch a whole family, naming conventions, and a library example. Level: intermediate.
  5. Python Assertions and Defensive Programming Reading What assert does and how to give it a message, why assertions catch your own bugs but must not check user input (they vanish under python -O), assert versus raise, guard clauses, preconditions, postconditions and invariants, and a score-parsing example. Level: intermediate.
  6. Python Context Managers and the with Statement Reading Why with guarantees cleanup, how it replaces try and finally, writing a context manager as a class (__enter__, __exit__) or with @contextmanager, suppressing errors, tools in contextlib, several managers in one with, and a rollback example. Level: advanced.
  7. Python Exception Chaining and Exception Groups Reading How raise from links a new error to its cause, implicit chaining with __context__, hiding the chain with from None, adding notes with add_note, and ExceptionGroup with except* for handling several errors at once, including split, nesting and the rules, with a validation example. Level: advanced.

15. Python Files, Paths, CSV and JSON

  1. Python Reading Text Files Reading How to open a text file with open(), why to use with and encoding="utf-8", the modes, and the ways to read: read(), readline(), readlines() and looping over the file line by line, stripping newlines, file positions with tell and seek, FileNotFoundError, and a log-file analyser. Level: basic.
  2. Python Writing and Appending Files Reading How to write text files with the w and a modes, write(), writelines() and print(file=), why w erases an existing file, exclusive creation with x, read-write modes, buffering and flush, saving safely with os.replace, and a to-do list saved between runs. Level: basic.
  3. Python with and Closing Files Reading Why every opened file must be closed, close() and the closed attribute, try and finally versus with, passing file objects to functions, in-memory files with io.StringIO for testing, files inside generators, and ExitStack for many files. Level: basic.
  4. Python Paths with pathlib Reading Absolute and relative paths, why pathlib.Path beats strings, building paths with /, reading name, stem, suffix and parent, checking and creating files and folders, read_text and write_text, rename and delete, and a report-saving example. Level: intermediate.
  5. Python Working with Folders Reading How to list folder contents with iterdir, find files with glob and rglob patterns, walk a whole tree with os.walk, copy, move and delete with shutil, filter by type or size, count files by extension, use temporary directories, and a download-folder organiser. Level: intermediate.
  6. Python CSV Files Reading What CSV files are and why not to split on commas, csv.reader and DictReader, csv.writer and DictWriter, the newline="" rule, quoting, other delimiters, values being text, bad rows, the BOM, and a marks-report example. Level: intermediate.
  7. Python JSON Reading What JSON is and how its types map to Python, dumps and loads, dump and load for files, indent and ensure_ascii, JSONDecodeError, what JSON cannot store (sets, dates) and default=, and a settings-file example. Level: intermediate.
  8. Python Binary Files and pickle Reading Bytes versus text, binary modes rb and wb, encoding and decoding, copying and hashing files in chunks, a look at struct, pickle for saving Python objects, why unpickling untrusted data is dangerous, and safer alternatives such as JSON. Level: advanced.

16. Python Modules, Packages and Environments

  1. Python Importing Modules Reading What a module is, the import forms (import x, from x import y, as), exploring a module with dir and help, ImportError versus ModuleNotFoundError, why import * is discouraged, how names clash, and that a module is loaded only once. Level: basic.
  2. Python Writing Your Own Module Reading How any .py file becomes a module, importing your own code, the if __name__ == "__main__" guard, running with python -m, docstrings and private names, shared state, the from-import copy trap, circular imports, and a temperature module. Level: intermediate.
  3. Python Packages and __init__.py Reading What a package is (a folder of modules), what __init__.py does, absolute and relative imports, sub-packages, re-exporting names, __all__, namespace packages, running package modules with python -m, and a small shop package. Level: intermediate.
  4. Python How Python Finds Modules Reading How Python searches for a module with sys.path (script folder, PYTHONPATH, standard library, site-packages), why the first match wins, shadowing by your own files, adding folders, find_spec, and a checklist for ModuleNotFoundError. Level: advanced.
  5. Python Virtual Environments Reading Why every project should have its own virtual environment, creating one with python -m venv, activating and deactivating it, running its Python directly, checking which environment is active, what is inside the folder, and keeping it out of git. Level: intermediate.
  6. Python pip and requirements.txt Reading Installing, upgrading, listing and uninstalling packages with python -m pip, version specifiers, dependencies, pip freeze and requirements.txt for reproducible environments, pinning versus ranges, and safety tips when choosing packages. Level: intermediate.

17. Python Standard Library

  1. Python datetime and time Reading Working with dates and times using date, time, datetime and timedelta, arithmetic and comparison, strftime, strptime and fromisoformat, naive versus timezone-aware values, UTC, zoneinfo, the time module, calendar helpers, and a payment-schedule example. Level: intermediate.
  2. Python random and secrets Reading Random numbers and choices with the random module (randint, choice, sample, shuffle, weighted choices), why they are pseudo-random, seeds, separate generators with random.Random, and why passwords and tokens need the secrets module. Level: intermediate.
  3. Python collections Counter, defaultdict and deque Reading The specialised containers in the collections module: Counter for counting, defaultdict for missing keys, deque for fast queues and sliding windows with maxlen, plus namedtuple, OrderedDict and ChainMap in brief. Level: intermediate.
  4. Python itertools Reading The itertools toolbox for working with iterators lazily: infinite counters (count, cycle, repeat), chain, islice, accumulate, takewhile and dropwhile, groupby (and why to sort first), product, permutations and combinations, pairwise and batched, zip_longest, tee, and starmap. Level: advanced.
  5. Python functools Reading functools helpers: lru_cache and cache to remember results, partial to fix arguments, reduce to fold a sequence, wraps to keep a decorator's metadata, singledispatch for type-based functions, cmp_to_key, and cached_property. Level: advanced.
  6. Python Regular Expressions Reading Describing text patterns with the re module: search, fullmatch, findall, sub and split, pattern syntax (classes, quantifiers, anchors, groups, greedy versus lazy, lookarounds), flags, compile, and examples that extract emails, phones and dates. Level: intermediate.
  7. Python os, sys and shutil Reading How a program talks to its surroundings: os for environment variables and the system, sys for arguments, platform and exit codes, shutil for copying and archives, subprocess for running other programs, with a backup-script example. Level: intermediate.
  8. Python Command-line Programs with argparse Reading Turning a script into a command-line tool with argparse: positional arguments, options, flags, types, defaults, choices, several values, subcommands, automatic help and errors, exit codes, a testable main function, and a word-frequency tool. Level: intermediate.
  9. Python logging Reading Why logging beats print, the five levels, basicConfig and format strings, named loggers, logging exceptions with tracebacks, handlers and formatters for console and file, propagation, library etiquette with NullHandler, and an orders example. Level: intermediate.
  10. Python sqlite3 Reading Storing and querying data with the built-in sqlite3 module: connecting, creating tables, inserting and selecting with ? placeholders, fetching rows, Row objects, commit and rollback, constraints, SQL injection, and an expense tracker. Level: intermediate.
  11. Python Fetching Data from the Web with urllib Reading How programs talk to web servers with the standard library: urllib.parse for URLs and query strings, urlopen and responses, JSON, headers, POST, HTTPError versus URLError, timeouts, retries and good manners. Examples run on a local server. Level: intermediate.

18. Python Testing and Debugging

  1. Python Debugging with print and pdb Reading A method for finding bugs, print debugging with f"{x=}" and pprint, the pdb debugger (breakpoint, next, step, continue, print, where, up, post-mortem), turning breakpoints off, and a worked example of a running-maximum bug. Level: intermediate.
  2. Python Testing with unittest Reading Why automated tests matter, writing test cases with unittest.TestCase and assert methods, running tests with python -m unittest, reading failures and errors, setUp and tearDown, testing exceptions, subTest, skipping, and replacing parts of a program with unittest.mock. Level: intermediate.
  3. Python Testing with pytest Reading Why many projects use pytest: plain assert with detailed failure messages, running and selecting tests, pytest.raises and approx, parametrize, fixtures and conftest.py, built-in fixtures (tmp_path, capsys, monkeypatch), markers, and running unittest tests. Level: intermediate.
  4. Python Designing Good Tests Reading What makes tests worth having: Arrange-Act-Assert, naming, edge cases and boundary values, making code testable, avoiding flaky tests, coverage and its limits, test-first development, and checking that tests can fail. Level: intermediate.
  5. Python Timing and Profiling Reading Measuring instead of guessing: timing with perf_counter and timeit, finding bottlenecks with cProfile, how running time grows with input size, measuring memory with tracemalloc and getsizeof, and making a duplicate finder far faster. Level: advanced.
  6. Python A Checklist for Common Bugs Reading A checklist of the bugs Python programmers meet most often, each with a tiny runnable example: off-by-one, changing a list while looping, shared lists, mutable defaults, is versus ==, float equality, shadowed built-ins, closures, and a review routine. Level: intermediate.

19. Python Type Hints and Code Quality

  1. Python Type Hints Reading What type hints are and are not (never enforced at run time), annotating variables, parameters and returns, list[str], X | None, Callable, Literal, TypedDict and Final, reading mypy messages, gradual adoption, and an example where mypy finds two bugs. Level: intermediate.
  2. Python Optional, Union, Generics and Protocols Reading Advanced type hints: unions, Optional and narrowing with isinstance, type variables and generic functions and classes (including class Box[T]), Protocols for structural typing instead of inheritance, runtime_checkable, and reading mypy's explanations. Level: advanced.
  3. Python PEP 8 and Formatting Tools Reading The Python style guide (PEP 8): naming, spacing, line length, imports and comparisons; linters and formatters (ruff, black), reading their reports, configuring them in pyproject.toml, and running them before each commit, with a messy-to-clean example. Level: intermediate.
  4. Python Documentation and Docstrings Reading How to document Python code: docstrings, one-line and multi-line forms, the Google, NumPy and reStructuredText styles, help() and pydoc, good and bad comments, doctest, README files, and a documented module whose examples are tested. Level: intermediate.
  5. Python Project Layout and Packaging Reading Organising a real Python project: the src layout, tests, README, pyproject.toml metadata, dependencies and console scripts, editable installs with pip install -e, building a wheel with python -m build, version numbers, and what publishing involves. Level: advanced.

20. Python Concurrency

  1. Python CPU-bound and I/O-bound Work Reading Why programs are slow in two ways: CPU-bound work that computes and I/O-bound work that waits, telling them apart with wall time versus CPU time, concurrency versus parallelism, and which Python tool fits which work. Level: intermediate.
  2. Python Threads Reading Running several flows of control with threading: start and join, why threads speed up waiting but not computing, race conditions and locks, queue.Queue, Event, daemon threads, errors in threads, and a worker-pool example. Level: advanced.
  3. Python Processes with multiprocessing Reading Using several cores with multiprocessing: Process, Pool.map and apply_async, the main-guard rule, pickling limits, Queue and shared Value with a Lock, start-up costs that make tiny tasks slower, and a prime-counting speed-up. Level: advanced.
  4. Python concurrent.futures Reading The friendly way to run work concurrently: ThreadPoolExecutor and ProcessPoolExecutor, map and submit, Future objects (result, exception, cancel, callbacks), as_completed and wait, timeouts, error handling, and switching threads for processes. Level: advanced.
  5. Python asyncio Reading Cooperative concurrency in one thread with async and await: coroutines, the event loop, asyncio.run, gather, create_task, TaskGroup, timeouts, Semaphore, queues, cancelling, to_thread, and the rule never to block the loop. Level: advanced.
  6. Python The GIL and Choosing a Concurrency Model Reading What the Global Interpreter Lock is and why it exists, measurements showing threads do not speed up pure Python but do help waiting, hashing and compression, why processes help, choosing threads, processes or asyncio, shared-state hazards, and free-threaded builds. Level: advanced.

21. Python Projects

  1. Python Project Number Guessing Game Reading A complete first project: a number guessing game made of small tested functions, input kept apart from logic, validation with ValueError, a limited number of tries, a scripted demo, unit tests, and ideas to extend it. Level: basic.
  2. Python Project To-do List in a File Reading A project that remembers: a to-do list stored as JSON, with a Task dataclass and a TodoList class, add, done, remove and clear commands, safe saving, friendly errors, a command loop kept apart from the logic, a demo run and tests. Level: intermediate.
  3. Python Project Expense Tracker with CSV Reading A project with real data handling: an expense tracker stored in a CSV file, validating dates and amounts, exact money with Decimal, safe appending, totals by category and month, errors with line numbers, and unit tests. Level: intermediate.
  4. Python Project Text Quiz Reading A data-driven quiz: questions stored in JSON and validated on loading, shuffled with a seeded random generator, input validation, scoring and grading, a review list, saved results with a top three, and tests using scripted answers. Level: intermediate.
  5. Python Project Command-line Tool with argparse Reading Build foldertool, a command-line tool with subcommands (summary, big, duplicates) using argparse, pathlib and hashlib: error messages on stderr, exit code 2, finding duplicates by size then hash, a testable main(argv), and tests. Level: advanced.
  6. Python What to Learn Next Reading A look back at the whole course as a map you can check yourself against, then what to do next: build your own projects, choose a direction (web, data, automation, testing), read other people's code, ask good questions, and keep a learning routine. Level: basic.