Lesson 7 of 8
Python's slogan is "batteries included." Before installing anything, check whether the standard library already does the job. Here are five modules worth knowing today.
math
import math
print(math.sqrt(16))
print(math.floor(3.7), math.ceil(3.2))
print(round(math.pi, 4))
print(math.pow(2, 10))
math.floor rounds down, math.ceil rounds up, and round() is a built-in that rounds to
nearest. Also useful: math.inf, math.factorial(n), math.gcd(a, b).
random
The module the Module 2 guessing game wanted:
import random
random.seed(42)
print(random.randint(1, 10))
print(random.choice(["rock", "paper", "scissors"]))
deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)
print(random.sample(range(1, 50), 3))
random.seed(42) makes the sequence reproducible — the same seed always gives the same
"random" numbers, which is exactly what you want in a test. Leave the seed out for genuinely
varying results.
randint(a, b) includes both ends, unlike range().
randomis fine for games and sampling, but not for security. Passwords and tokens need thesecretsmodule instead.
datetime
import datetime
d = datetime.date(2026, 1, 15)
print(d)
print(d.year, d.month, d.day)
later = d + datetime.timedelta(days=30)
print(later)
print((later - d).days)
date is a day, datetime a day plus time, and timedelta a duration you can add or subtract.
Subtracting two dates gives a timedelta. Module 9 covers this properly.
Formatting uses strftime:
import datetime
d = datetime.date(2026, 1, 15)
print(d.strftime("%d/%m/%Y"))
print(d.strftime("%B %d, %Y"))
os
Interacting with the operating system, mostly paths and files:
import os
os.makedirs("demo/sub", exist_ok=True)
with open("demo/sub/file.txt", "w") as f:
f.write("hi")
print(os.path.exists("demo/sub/file.txt"))
print(os.path.basename("demo/sub/file.txt"))
print(os.path.splitext("report.csv"))
print(sorted(os.listdir("demo")))
os.path.join("a", "b") builds paths with the right separator for the platform — always prefer
it over "a" + "/" + "b".
os.environ reads environment variables, the standard way to pass configuration and secrets to
a program:
import os
print(os.environ.get("MY_SETTING", "not set"))
Use .get() with a default so a missing variable doesn't crash you.
Modern code often uses pathlib instead, which is more object-oriented:
from pathlib import Path
p = Path("demo") / "sub" / "file.txt"
print(p.name)
print(p.suffix)
print(p.parent.name)
The / operator joins paths. Both are fine; pathlib reads better for path-heavy work.
sys
Information about the interpreter itself:
import sys
print(sys.version_info.major)
print(isinstance(sys.path, list))
print(sys.platform.startswith(("linux", "darwin", "win", "emscripten")))
The two you'll actually use are sys.argv — command-line arguments, which you'll need for CLI
tools — and sys.exit(1) to stop with an error code.
Others worth a look
| Module | For |
| --- | --- |
| collections | Counter, defaultdict, deque |
| itertools | combinations, permutations, grouping |
| re | regular expressions (Module 9) |
| unittest | testing (Module 9) |
| statistics | mean, median, stdev |
| textwrap | wrapping and indenting text |
collections.Counter deserves a mention — it replaces the counting loop you wrote in Module 3:
from collections import Counter
counts = Counter("banana")
print(counts["a"])
print(counts.most_common(2))
Try it yourself
Checkpoint
- Check the standard library before installing a package.
mathfor numbers,randomfor chance (seed it for reproducibility).datetimefor dates andtimedeltafor durations.osfor paths, files, and environment variables;pathlibis the modern alternative.sysfor interpreter and command-line details;collectionsfor better containers.
Questions about this lesson
Log in to ask a question.