A Tour of the Standard Library
Intermediate · 18 min read · ▶ live playground · ✦ checkpoint
You can build a useful Python script before installing anything extra. The standard library is Python's built-in toolbox, a set of modules that ships with Python: numbers, chance, dates, paths, JSON, and specialized collections are already on the wall.
The trick is not memorizing every tool. It is learning which drawer to open first.
Numbers, chance, and summaries
You already met math for square roots and rounding. Pair it with random and statistics, and you can handle many small data jobs.
A seed is a starting value that makes random produce the same sequence again. Real games often avoid fixed seeds. Lessons and tests use them so the output stays predictable.
import math
import random
import statistics
random.seed(7)
scores = [82, 91, 77, 91]
bonus = random.choice([3, 5, 8])
adjusted_scores = []
for score in scores:
adjusted_scores.append(score + bonus)
print("bonus:", bonus)
print("adjusted:", adjusted_scores)
print("average:", statistics.mean(adjusted_scores))
print("round up:", math.ceil(statistics.mean(adjusted_scores)))
print("middle:", statistics.median(adjusted_scores))bonus: 5adjusted: [87, 96, 82, 96]average: 90.25round up: 91middle: 91.5
random.choice(...) picks one item from a collection. statistics.mean(...) gives the average, and statistics.median(...) gives the middle value. math.ceil(...) rounds up when your program needs a whole number.
Use these modules together when a program says, "pick something, score it, summarize it."
Dates and clocks
The datetime module handles calendar dates and clock times. A timedelta is a difference between two dates or times, like "3 days later."
The time module works closer to raw clock values. You will see it in scripts that measure elapsed seconds or format system time.
from datetime import datetime, timedelta
import time
practice_start = datetime(2026, 7, 2, 18, 30)
review_day = practice_start + timedelta(days=3)
fixed_time = time.gmtime(0)
print(practice_start.strftime("%b %d, %Y %H:%M"))
print(review_day.strftime("%A"))
print(time.strftime("%Y-%m-%d", fixed_time))Jul 02, 2026 18:30Sunday1970-01-01
strftime(...) formats a date or time into text. The last print formats the fixed time value 0, so the output does not depend on the real clock.
Use datetime when your story is about calendar meaning: a practice day, a birthday, a deadline. Use time when your story is closer to the clock itself: waiting, measuring, or formatting a raw time value.
Paths and Python itself
A path is a location for a folder or file. The pathlib module gives you Path objects, path values with useful attributes such as .name and .suffix.
An operating system is the software that manages your computer's files, programs, and devices. os gives Python a careful bridge to operating-system tools. sys gives facts about the Python runtime, which means the Python program currently running your code.
import os
import sys
from pathlib import Path
score_path = Path("course") / "scores" / "week1.json"
print(score_path.as_posix())
print(score_path.name)
print(score_path.suffix)
print(os.path.splitext(score_path.name)[0])
print(sys.version_info.major)course/scores/week1.jsonweek1.json.jsonweek13
The / operator joins path parts when the left side is a Path. That line does not create a file. It builds a path value your program can pass around.
Prefer pathlib for new path-handling code. Reach for os when you need older path helpers or operating-system facts. Reach for sys when you need information about Python itself, such as the version.
JSON turns data into text
JSON is a text format for data shaped like dictionaries, lists, strings, numbers, booleans, and missing values. It is common because many languages can read it.
Python data and JSON text are not the same thing. json.dumps(...) turns Python data into a JSON string. json.loads(...) turns a JSON string back into Python data. The s means "string."
import json
player = {
"name": "Mina",
"score": 91,
"badges": ["helper", "fast finisher"],
"active": True,
}
json_text = json.dumps(player, sort_keys=True)
restored = json.loads(json_text)
print(json_text)
print(restored["name"])
print(restored["badges"][0]){"active": true, "badges": ["helper", "fast finisher"], "name": "Mina", "score": 91}Minahelper
Notice the lowercase true inside the JSON text. Python uses True; JSON uses true. json.loads(...) handles that translation for you.
Reading and writing JSON files comes in lesson 9.2. For now, keep the idea clean: JSON is portable text, and the json module converts between that text and Python data.
Specialized collections
The collections module gives you collection tools for jobs that plain lists and dictionaries can do, but less neatly.
Counter is a dictionary-like tally tool for counting items. It is like tally marks on a clipboard: each repeated item adds one mark. defaultdict is a dictionary that creates a default value for a missing key. deque is a two-ended queue, a line where items can enter or leave from either end efficiently. namedtuple creates tuple records whose positions also have field names.
from collections import Counter, defaultdict, deque, namedtuple
snacks = ["apples", "tea", "apples", "mangoes", "tea", "apples"]
counts = Counter(snacks)
moods = defaultdict(list)
for player, mood in [("Mina", "focused"), ("Ravi", "calm"), ("Noor", "focused")]:
moods[mood].append(player)
line = deque(["Mina", "Ravi"])
line.append("Noor")
first_player = line.popleft()
PlayerCard = namedtuple("PlayerCard", ["name", "score"])
card = PlayerCard("Ira", 42)
print(counts.most_common(2))
print(dict(moods))
print(first_player)
print(list(line))
print(card.name, card.score)[('apples', 3), ('tea', 2)]{'focused': ['Mina', 'Noor'], 'calm': ['Ravi']}Mina['Ravi', 'Noor']Ira 42
These tools save code when the shape already matches the problem. Counting repeated snacks? Counter. Grouping players by mood? defaultdict(list). Managing a line? deque. Want a tiny fixed record with names? namedtuple.
Try it - build a small report
Run this report, then change the players or the seed. Notice how each module has one job.
This is the standard library in real use: one module for chance, one for counting, one for dates, one for paths, one for JSON text. You keep the program readable by choosing the smallest tool that matches the job.
Checkpoint
Answer all three to mark this lesson complete
The standard library is your first stop before reaching outside Python. Next, you will stop only borrowing modules and start organizing your own code into modules and packages, folders of related modules.