Python exercises
Small tasks with a starter, a hint and a solution. Your answer is run and checked in the browser, so the result is what Python actually did.
Exercise sets
Syntax
Indentation is the structure. Here is what that means in practice.
Variables
Names that point at values, and what assignment really does.
Multiple Assignment
Assign several names at once, unpack a sequence, and swap without a temporary.
Data Types
The built-in types you will actually use, and how to ask what something is.
Numbers
Integers, floats, the two kinds of division, and why 0.1 + 0.2 misbehaves.
Casting
Converting between types on purpose, and where conversion fails.
Booleans
True, False, and the rule that decides whether any value counts as either.
Operators
Arithmetic, comparison, logic, membership and identity, plus what binds tightest.
User Input
Read something the person running your program typed, and convert it safely.
Introduction
What Python is, what it is good at, and what you need before you start.
Get Started
Install Python, run a file, and use the interactive prompt.
Comments
Notes to humans that the interpreter skips, and how to use them well.
Variable Names
What Python allows, what it forbids, and what other people expect.
Global Variables
Names defined outside a function, and the keyword you need to change one.
Strings
Text in Python, the quotes you can use, and the fact that strings never change.
Slicing
Take a piece out of a string with start, stop and step.
Modify Strings
Change case, trim whitespace and replace text - always by making a new string.
Concatenation
Joining strings with +, repeating with *, and why numbers need converting first.
f-Strings
Put values straight into text, and format them while you are there.
String Formatting
format(), the older % style, and how to line text up in columns.
Escape Characters
Backslashes for newlines, tabs and quotes, and the raw strings that switch them off.
String Methods
The methods you will actually reach for, grouped by what you want done.
Lists
An ordered, changeable run of items - the collection you will use most.
List Access
Get items out by position, from either end, and in slices.
Change Items
Replace one item or a whole slice, in place.
Add Items
append, insert and extend, and the difference between them.
Remove Items
remove, pop, del and clear, and which one to reach for.
Loop Lists
Walk a list properly, with the index when you need it and without when you do not.
List Comprehension
Build a list from another one in a single readable line.
Sort Lists
sort in place or sorted into a new list, with a key and a direction.
Copy Lists
Why assignment does not copy, and the difference between shallow and deep.
Join Lists
Put two lists together, and turn a list into a string.
List Methods
The full set of list methods, and which return a value rather than None.
Tuples
An ordered sequence that cannot change, and why that is useful.
Sets
An unordered collection with no duplicates, and fast membership tests.
Dictionaries
Look values up by a key instead of a position.
Nested Dictionaries
Dictionaries inside dictionaries, and how to read them without crashing.
If...Else
Run code only when a condition holds, and choose between branches.
Match
Structural pattern matching, and where it beats a chain of elif.
While Loops
Repeat while a condition holds, and make sure it eventually stops.
For Loops
Walk a sequence, count with range, and loop over dictionaries.
Break and Continue
Leave a loop early, or skip the rest of one pass.
Functions
Name a piece of work once and run it whenever you need it.
Arguments
Positional and keyword arguments, and how Python matches them up.
args and kwargs
Accept any number of positional or keyword arguments.
Default Values
Make a parameter optional, and avoid the shared-default trap.
Return Values
Hand a result back, return several things, and leave early.
Scope
Where a name is visible, and the order Python searches.
Recursion
A function that calls itself, and the base case that stops it.
Lambda
A small unnamed function, and when a def is the better choice.
Classes and Objects
Bundle data and the code that works on it into one thing.
The __init__ Method
Set up each new object with the data it needs.
The __str__ Method
Decide what your object looks like when it is printed.
Methods
Functions that belong to a class, and the three kinds of them.
self
What self actually is, and why you have to write it.
Inheritance
Build a class on top of another, and override what differs.
Polymorphism
Different types answering the same call, and why Python barely notices.
Iterators
How for loops actually work, and how to make your own object loopable.
Modules
Split code across files, and pull in what the standard library already has.
Dates
Points in time, differences between them, and turning them into text.
Math
The math module, plus statistics and random.
JSON
Turn Python data into text and back, for files and APIs.
RegEx
Find and replace text by pattern rather than by exact match.
File Handling
Open a file safely, in the right mode, with the right encoding.
Read Files
Read a whole file, a line at a time, or lazily for a big one.
Write Files
Create, overwrite and append, without losing what was there.
Delete Files
Remove files and folders, and check first without a race.
Try...Except
Handle the errors you expect, and let the rest surface.
Raising Exceptions
Signal a problem yourself, and define your own exception types.
Type Hints
Say what types you expect, for readers and for tools.
Text and Unicode
What a character really is, and the difference between text and bytes.
Dictionary Methods
The full set of dict methods, and which ones change the dictionary.
Set Methods
Adding, removing, and the four ways to compare two sets.
Dict and Set Comprehensions
Build a dictionary or a set in one line, the same way you build a list.
The collections Module
Counter, defaultdict, deque and namedtuple, and when each is the right tool.
Decorators
Wrap a function to add behaviour, without editing the function.
Generators
Produce values one at a time instead of building a whole list.
Closures
A function that remembers the variables it was built with.
Dataclasses
Let Python write __init__, __repr__ and __eq__ for a class that holds data.
Enums
A fixed set of named values, instead of loose strings scattered about.
Magic Methods
The dunder methods that make your class work with Python's own syntax.
itertools
Building blocks for looping, that never build the whole sequence.
os and sys
Talk to the operating system: environment, paths, and the running interpreter.
Random Numbers
Pick, shuffle and sample, and know when random is not good enough.
CSV Files
Read and write comma-separated data without breaking on quoted commas.
Context Managers
Guarantee that cleanup happens, even when something goes wrong.
Paths with pathlib
Build, inspect and search file paths without worrying about slashes.
Testing
Write code that checks your code, so a change cannot break it quietly.
Logging
Keep a record of what your program did, with levels you can turn up or down.
Command-line Arguments
Turn a script into a proper tool with argparse.
Debugging
Read a traceback, then find the problem with a debugger instead of guessing.
SQLite
A real database in a single file, with no server, built into Python.
Your First Model
Load data, train, predict and score, in fifteen lines.
Features and Labels
Shaping your data into the grid of numbers a model expects.
Train and Test Split
Hold data back, or you cannot tell whether the model learned anything.
Classification
Predicting which category something belongs to.
Regression
Predicting a number rather than a category.
Evaluating a Model
Accuracy hides more than it shows. What to look at instead.
Overfitting and Underfitting
Memorising the training data, or not learning it at all.
Preprocessing
Scaling numbers, encoding categories and filling gaps.
Pipelines
Chain preprocessing and model into one object that cannot leak.
Clustering
Finding groups in data that has no labels at all.
Neural Networks
What a network actually is, and when it beats simpler models.
Saving and Using a Model
Get a trained model out of your notebook and into something that runs.
Where It Goes Wrong
The mistakes that make a model look far better than it is.