Python Book

Python for your first year

Twelve short, free chapters that take you from installing Python to writing classes and testing your code. Each chapter ends with exercises and answers you can check.

Part 1: the basics

  1. Getting started Install Python, run your first program and use the interactive shell.
  2. Variables and types Numbers, strings and booleans, converting between them, and f-strings.
  3. Making decisions Comparisons, if, elif and else, and combining conditions.
  4. Loops for, while and range, plus break and continue.
  5. Functions Define your own functions with parameters, return values and defaults.
  6. Lists and dictionaries Store collections of data, slice them, loop over them and look things up.

Part 2: beyond the basics

  1. More functions *args and **kwargs, lambdas, sorting with a key, recursion and type hints.
  2. Dictionaries and sets Comprehensions, Counter, defaultdict, set operations and nested data.
  3. Working with files Read and write text files, use pathlib, and handle CSV and JSON.
  4. Classes and objects Build your own types with methods, special methods, inheritance and dataclasses.
  5. Errors and exceptions Read tracebacks, handle failures with try, and raise your own exceptions.
  6. Testing your code Check your code automatically with assert and pytest, and pick good test cases.

How to use this book

The examples use Python 3.10 or newer.