Sikau

Python · Day 10 · about 45 min

Capstone: The standard library

Modules, collections, itertools and pathlib in an expense report.

Batteries included

Python's slogan is "batteries included": it ships with a large standard library of modules for files and paths, dates, JSON and CSV, maths and statistics, random numbers, regular expressions, and smarter collections. Before you write a helper, it's worth asking whether Python already has one.

For the capstone you'll build an expense tracker's report — loading records, totalling by category, finding the biggest spends and summarising file types — in a few lines each, by leaning on collections and pathlib instead of writing everything by hand.

Modules and imports

A module is simply a .py file; a folder of modules (with an __init__.py) is a package. import math gives you the module as a name, so you write math.sqrt(2). from collections import Counter imports one name directly. import numpy as np renames on import. Third-party packages are installed with pip from PyPI; the standard library is always there.

When Python runs a file directly, that file's __name__ is "__main__"; when it's imported, __name__ is the module's name. That's what the common if __name__ == "__main__": guard is for — code under it runs as a script but not on import, so the same file can be both a tool and a library.

import math
from statistics import mean
from datetime import date

print(math.sqrt(16), mean([180, 25, 40]))
print(date(2026, 10, 1).strftime("%A %d %B"))
print(__name__)

The rest of this lesson

  • collections, itertools and pathlibexplain
  • Counting letterspredict
  • Which module?match
  • Total by categoryfill
  • The expense reportchallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Python