Python course / Working Python
Standard library tour
Learn the parts of the standard library worth knowing by name, and reach for them before writing your own. Most of what a small program needs already ships with Python, and the habit this builds is looking first.
- itertools
- functools
- enum
- regular expressions
- argparse
- random vs secrets
- hashing
- decimal
Runs in your browser. Start straight away; create an account when you want your progress kept.
import re
from decimal import Decimal
from functools import cache
from itertools import accumulate
@cache
def steps(count):
return 1 if count < 2 else steps(count - 1) + steps(count - 2)
print("running totals:", list(accumulate([3, 5, 2])))
print("exact money:", Decimal("0.10") * 3)
print("found:", re.findall(r"[a-z]+", "tea, jam and oats"))
print("cached recursion:", steps(30))
running totals: [3, 8, 10] exact money: 0.30 found: ['tea', 'jam', 'and', 'oats'] cached recursion: 1346269
What you will learn
- Look for the standard library's answer before writing your own, and know where to look.
- Join, cut, pair and group sequences of items with the four itertools you will use most.
- Fix some of a function's arguments in advance, and remember answers a function has already worked out.
- Find and take apart text with a pattern, and recognise when a pattern is the wrong tool.
- Make repeatable random choices for simulations and tests, and unguessable ones for anything secret.
- Do exact decimal arithmetic and rounding for money, and exact fractions, where floats cannot.
The lessons in this module
- How to find what already exists
- itertools: the basics
- functools: partial and cache
- enum: a fixed set of choices
- Regular expressions: matching and groups
- Regular expressions: substituting, naming, compiling
- argparse: a script's command line
- textwrap and string
- random, and why secrets exists
- hashlib, hmac and base64
- decimal and fractions: exact arithmetic
- time and timeit: measuring code
- shutil and tempfile: whole folders, and scratch space
- Reading the standard library's own source
- Capstone: the hand-made toolbox
- Module review: the day's takings
Ready when you are
Previous: Type hints. Next: Iterators and generators. All modules are on the course page.