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
- Getting started Install Python, run your first program and use the interactive shell.
- Variables and types Numbers, strings and booleans, converting between them, and f-strings.
-
Making decisions
Comparisons,
if,elifandelse, and combining conditions. -
Loops
for,whileandrange, plusbreakandcontinue. - Functions Define your own functions with parameters, return values and defaults.
- Lists and dictionaries Store collections of data, slice them, loop over them and look things up.
Part 2: beyond the basics
-
More functions
*argsand**kwargs, lambdas, sorting with a key, recursion and type hints. -
Dictionaries and sets
Comprehensions,
Counter,defaultdict, set operations and nested data. -
Working with files
Read and write text files, use
pathlib, and handle CSV and JSON. - Classes and objects Build your own types with methods, special methods, inheritance and dataclasses.
-
Errors and exceptions
Read tracebacks, handle failures with
try, and raise your own exceptions. -
Testing your code
Check your code automatically with
assertand pytest, and pick good test cases.
How to use this book
- Type the examples yourself instead of copying them. Your fingers learn the syntax faster than your eyes do.
- Try every exercise before opening the answer. Getting stuck for a few minutes is part of learning.
- When you finish, practise with the daily problem. Many of the easy ones use only what is in this book.
The examples use Python 3.10 or newer.