Topic 02

The Standard Library

Hands-on

Python ships with hundreds of modules for everyday jobs: dates, randomness, maths, statistics, files, data formats, even talking to the internet. This collection is the standard library, and it is why Python is often described as "batteries included". Most scripts need nothing installed at all, as long as you know how to find what is already there.

Think of moving into a furnished flat. Before buying a kettle, you open the cupboards. The standard library is the cupboards, and a quick look through them saves both money and the risk of bringing home something you did not need.

What Ships with Python

You have already used several standard modules: decimal for money, csv for spreadsheet files, json for data, pathlib for paths. A few more come up again and again. random makes random choices. statistics does averages, medians and spreads. math has square roots, rounding up and down, and constants like pi. datetime handles dates and times, and has the next topic to itself.

A Few in Action

The program below uses three of them. statistics.median gives the middle value of a week of temperatures, which, unlike the average, is not dragged up by one unusually hot day. math.ceil rounds up, which is what you want when you need 20 guests at tables of 6: three tables are not enough, so the answer is four.

tools.py
import math
import statistics

temps = [18, 22, 25, 19, 30, 27, 21]
print("Median temperature:", statistics.median(temps))
print("Mean temperature:", round(statistics.mean(temps), 1))

guests = 20
seats_per_table = 6
print("Tables needed:", math.ceil(guests / seats_per_table))
Output
Median temperature: 22
Mean temperature: 23.1
Tables needed: 4

random.choice picks one item from a list, and random.shuffle puts a list in a random order. Because the result is random, your output will differ from the one below, which is exactly the point.

draw.py
import random

names = ["Anna", "Omar", "Lena", "Sam"]
print("This week's winner:", random.choice(names))
One possible output
This week's winner: Lena

One note of care: random is fine for games, draws and tests, and wrong for anything secret, such as passwords or security codes. For those, the standard library has a separate module, secrets. This book does not need it, but you should know it exists.

Finding the Rest

The official documentation at docs.python.org lists every standard module in a page called The Python Standard Library. Each module has its own page, and every one starts the same way: a short summary of what the module is for, followed by its functions, each with a description and usually an example. Reading one of these pages is a skill worth practising. It outlasts any course, including this one.

Before You Install Anything

When you need a new capability, search the standard library first. If it is there, you get code that is maintained alongside Python itself, documented in one place, and installed on every computer that has Python. The next two topics are about installing other people's packages, and that is the right move only when the standard library genuinely does not cover the job.

A job, and the standard module that does it
You need toModuleExample
count money exactlydecimalDecimal("4.20")
read a spreadsheet exportcsvcsv.DictReader(f)
save and load structured datajsonjson.dump(data, f)
work with pathspathlibPath("data") / "notes.txt"
find a median or meanstatisticsstatistics.median(values)
pick at randomrandomrandom.choice(names)
work with datesdatetimedate.today()
Common Confusions
  • "Useful tools always have to be installed." A large set comes with Python. Check the standard library before installing anything.
  • "The official documentation is written for experts." Every module page starts with a plain summary and examples. It is the most reliable reference there is.
  • "random is fine for passwords." It is predictable enough to be unsafe for secrets. Use the secrets module for anything security-related.
Why It Matters
  • Knowing what is included saves installing, and having to trust, extra code.
  • Reading official documentation is the skill that keeps working long after any course ends.

Knowledge Check

Which of these modules comes with Python, with nothing to install?

  • statistics, for medians and means
  • requests, for talking to web services
  • pytest, for running automated tests
  • numpy, for fast work with large numbers

How many tables does math.ceil(20 / 6) say are needed?

  • 3, because 20 divided by 6 is 3 and a bit
  • 4, because ceil always rounds up
  • 3.33, the exact result of the division
  • 2, the remainder left after dividing

Why should you not use random to make a password?

  • It can only ever choose from lists of names, not letters
  • It is too slow to generate long passwords that are safe enough
  • Its choices are predictable enough to be unsafe for secrets
  • It gives the same answer on every single run

What should you do before installing a package for a new job?

  • Ask whether the job could be done without using Python at all
  • Install several packages and compare them
  • Write the whole feature yourself from scratch
  • Check whether the standard library already does it

You got correct