Python ships with a large standard library — the "batteries included" its users have bragged about for thirty years. Knowing what is in the box saves you from writing it again.
Four ways to import
import math # the whole module
print(math.sqrt(16), math.pi)
from math import sqrt, pi # specific names
print(sqrt(25), pi)
import statistics as stats # with a shorter alias
print(stats.mean([1, 2, 3, 4]))
from math import * # everything - do not do this
print(cos(0))Prefer the first two. import math keeps the origin of math.sqrt visible;
from math import * dumps unknown names into your namespace and quietly
shadows your own.
math and random
import math
import random
print(math.sqrt(144), math.floor(3.7), math.ceil(3.2))
print(math.factorial(5), round(math.log(100, 10)))
random.seed(7) # same seed, same sequence - handy for tests
print(random.randint(1, 6))
print(random.random())
print(random.choice(["rock", "paper", "scissors"]))
deck = list(range(1, 11))
random.shuffle(deck)
print(deck)
print(random.sample(deck, 3))datetime
from datetime import date, datetime, timedelta
today = date(2026, 1, 9)
print(today, today.year, today.strftime("%A, %d %B %Y"))
launch = date(2026, 3, 1)
gap = launch - today
print(f"{gap.days} days until launch")
print(today + timedelta(days=90))
parsed = datetime.strptime("2026-01-09 14:30", "%Y-%m-%d %H:%M")
print(parsed, parsed.hour)strftime formats a date into text; strptime parses text into a date. The
codes are the same both ways: %Y four-digit year, %m month, %d day, %H
hour, %M minute, %A weekday name, %B month name.
json
JSON is how programs exchange structured data. The mapping to Python is almost one to one: objects become dictionaries, arrays become lists.
import json
data = {
"name": "Ada",
"languages": ["Python", "Analytical Engine"],
"active": True,
"score": None,
}
text = json.dumps(data, indent=2) # Python -> JSON text
print(text)
restored = json.loads(text) # JSON text -> Python
print(type(restored), restored["languages"][0])
print(restored["active"] is True, restored["score"] is None)Note the translation: Python's True becomes true, None becomes null.
json.dump() and json.load() (no "s") do the same to and from a file.
You open the file with with open(...), exactly as in the Files lesson, and
pass the file object instead of getting text back:
import json
summary = {"total": 35, "rejected": 2}
with open("summary.json", "w", encoding="utf-8") as file:
json.dump(summary, file) # Python -> JSON, written to the file
with open("summary.json", encoding="utf-8") as file:
restored = json.load(file) # JSON read from the file -> Python
print(restored["total"], restored["rejected"])This is the round trip the Day 5 checkpoint asks for: save a result, read it back, and check you got the same values.
collections.Counter
Counter is the word-count loop from Day 3 in a single call.
from collections import Counter
words = "the quick brown fox the lazy dog the end".split()
counts = Counter(words)
print(counts.most_common(2))
print(counts["the"], counts["missing"]) # missing keys are 0, not an errormost_common(2) gives the two most frequent items with their counts, highest
first. A Counter is a dictionary underneath, so counts["the"] works as you
would expect, except that a word it never saw counts as 0 instead of raising
KeyError.
pathlib
The modern way to handle paths — no string concatenation, no separators to get wrong.
from pathlib import Path
folder = Path("data")
folder.mkdir(exist_ok=True)
note = folder / "note.txt" # / joins paths on any OS
note.write_text("Written through pathlib\n")
print(note)
print(note.name, note.suffix, note.stem)
print(note.exists())
print(note.read_text())
for item in folder.iterdir():
print(" found:", item)Writing your own module
Any .py file is a module. The next playground holds two files — click the
tabs above the editor to switch between them.
Imports look in the same folder first, so from geometry import ... finds
geometry.py sitting next to main.py. That is all a module is.
Don't name your file after a module
Imports look in your own folder first. Save your practice file as
random.py or json.py, and import random finds your file instead of
the standard library, so random.randint fails with
AttributeError: module 'random' has no attribute 'randint'. If a standard
module suddenly seems to have lost its functions, check for a file with the same
name next to yours, rename it, and delete any __pycache__ folder beside it.
if __name__ == '__main__'
Code at the top level of a module runs on import. Guarding it with
if __name__ == "__main__": means it runs only when the file is executed
directly — so a module can be both an importable library and a runnable script.
Before you write your own
Predict. Four modules' worth of lines. The date one crosses a month.
from collections import Counter
from datetime import date, timedelta
import json
meals = Counter(["pasta", "rice", "pasta", "soup", "pasta"])
print(meals.most_common(1))
print(meals["pizza"])
start = date(2026, 1, 30)
print(start + timedelta(days=3))
print(json.dumps({"done": True, "note": None}))Check your prediction
[('pasta', 3)]
0
2026-02-02
{"done": true, "note": null}A Counter answers 0 for something it never saw, rather than raising.
timedelta handles month ends for you. And JSON spells Python's True and
None as true and null.
Fix. A to-do list saved as JSON should come back as a list you can loop over. Instead this prints one character per line.
import json
tasks = ["buy milk", "call Sam"]
text = json.dumps(tasks)
for task in text:
print(task)Check your fix
import json
tasks = ["buy milk", "call Sam"]
text = json.dumps(tasks)
for task in json.loads(text):
print(task)buy milk
call Samjson.dumps returns a string — that's what makes it saveable — and looping
over a string gives you its characters. json.loads turns the text back into a
list.
A dice-rolling report
Roll two six-sided dice 1,000 times and report how often each total from 2 to 12 came up, as a percentage to one decimal place. Seed the generator with 42 so your run is reproducible.
You should get eleven lines, one for each total from 2 to 12, with 7 the most
common — in the long run it comes up one time in six, so expect roughly 15 to
18%. Your exact percentages depend on the order you call random in, so they
may not match the solution's to the digit.
import random
from collections import Counter
random.seed(42)
# Your code hereHint 1: the idea
Two parts: simulate, then report. One roll of two dice is
random.randint(1, 6) + random.randint(1, 6). Doing that 1,000 times and
counting how often each total appears is exactly what Counter is for. The
report is then a loop over the totals 2 to 12.
Hint 2: a first step
Make one roll and print it. Then collect 1,000 of them in a list, and pass the
list to Counter — print that, and you'll see every total with its count. A
count out of 1,000 becomes a percentage when you divide by 10.
Show one solution
import random
from collections import Counter
random.seed(42)
rolls = Counter(
random.randint(1, 6) + random.randint(1, 6)
for _ in range(1000)
)
for total in range(2, 13):
count = rolls[total]
bar = "#" * (count // 10)
print(f"{total:2}: {count / 10:5.1f}% {bar}")A generator expression feeding Counter does the whole simulation in one
statement, and rolls[total] returns 0 for any total that never came up.
Day 5 checkpoint: combine today's ideas
Close the worked examples and try this from memory. It takes about 15–20 minutes.
A saved minutes report
The starter writes one duration per line to minutes.txt. Read the file, skip blank lines silently, and accept nonnegative whole minutes. Count invalid text and negative values as rejected lines. Save total and rejected in summary.json, read that JSON back, then print the restored values. Conversion and rejection belong before accumulation, so a bad line cannot enter the total. Your program should print exactly:
Total: 35
Rejected: 2When your output matches, try these changes. Each says what to change and what you should then see:
| Change the file to | What you should see |
|---|---|
"\n\n" (blank lines only) | Total: 0 and Rejected: 0 |
"0\n1.5\n" | Total: 0 and Rejected: 1: zero is fine, 1.5 isn't whole minutes |
"25\noops\n10\n" | Total: 35 and Rejected: 1: the bad line doesn't stop the good ones |
with open("minutes.txt", "w", encoding="utf-8") as file:
file.write("25\n\noops\n-5\n10\n")
# Read, validate, summarize, save JSON, and restore it.Hint 1: the idea
Handle one conversion failure per line so later valid lines still count. JSON saving and restoring are separate from the counting rules.
Hint 2: a first step
Skip stripped empty text first. Catch ValueError only around int conversion, then check the numeric range before adding.
Show one solution
import json
with open("minutes.txt", "w", encoding="utf-8") as file:
file.write("25\n\noops\n-5\n10\n")
total = 0
rejected = 0
with open("minutes.txt", encoding="utf-8") as file:
for line in file:
text = line.strip()
if not text:
continue
try:
minutes = int(text)
except ValueError:
rejected += 1
continue
if minutes < 0:
rejected += 1
continue
total += minutes
with open("summary.json", "w", encoding="utf-8") as file:
json.dump({"total": total, "rejected": rejected}, file)
with open("summary.json", encoding="utf-8") as file:
restored = json.load(file)
print(f"Total: {restored['total']}")
print(f"Rejected: {restored['rejected']}")Total: 35
Rejected: 2Close the solution and change one input. Explain which case would expose the mistake you were most likely to make. Begin your next session by rebuilding one small part without looking back.
Going further: two more collections tools
Nothing later in the course needs these, but you'll meet them in other people's code.
from collections import defaultdict, namedtuple
words = "the quick brown fox the lazy dog the end".split()
groups = defaultdict(list) # list is the factory: a new key starts as list()
for word in words:
groups[len(word)].append(word)
print(dict(groups))
Point = namedtuple("Point", ["x", "y"]) # a tuple whose fields have names
p = Point(3, 4)
print(p, p.x, p.y)defaultdict(list) takes a type, not a list: whenever you read a key that
isn't there yet, it calls list() to make an empty list, stores it, and hands
it to you, so .append always has something to append to. namedtuple
builds a small tuple type whose items you can reach by name; Day 6's dataclasses
do the same job with more room to grow.
What you learned
import moduleandfrom module import nameare the imports to use.math,random,datetime,json,collectionsandpathlibcover an enormous amount of everyday work.- JSON maps onto Python dictionaries and lists almost exactly.
Countercounts in one call; a missing key counts as 0.- Don't name your own file after a standard module: yours is found first.
- Any
.pyfile next to yours is importable as a module.