← Learning Hub
Beginner

Modules and the Standard Library

A module is a file of ready-made code. Python comes with many useful ones. Bring them in with import.

Nobody writes everything from scratch. Python comes with a standard library - a large set of modules for maths, dates, random numbers, files, internet, and much more. Using them saves time, and they're well tested, so they have fewer bugs than code you'd write yourself.

import math brings in the whole module; you then write math.sqrt(). from datetime import date brings in just one part, so you can write date() directly. Both are common.

Example
You can edit this code.

Dates

Example
You can edit this code.

Dates are trickier than they look: months have different lengths, there are leap years, and formats differ between countries. The datetime module handles all of that. timedelta is a length of time you can add or subtract, like "4 days".

Random choices

The random module picks random values, so its output changes every time you run it:

Example
import random
print(random.randint(1, 6))          # a dice roll
print(random.choice(["Red", "Blue"]))

Installing more packages

Thousands of extra packages are on PyPI. Install them in a terminal with pip:

PyPI (the Python Package Index) is a free online store of packages written by people around the world. pip downloads and installs them. Popular ones: requests (talk to websites), pandas (data tables), flask (websites). Only install packages you trust - check they're popular and maintained.

Example
pip install requests
You can write your own module too: save functions in shop.py, then use import shop in another file in the same folder.
Key points
  • Modules are files of ready-made code; bring them in with import.
  • The standard library includes math, datetime, random and many more.
  • Install extra packages from PyPI with pip install name.

📝 Test yourself

1. Which keyword brings in a module?
2. Which tool installs extra Python packages?
3. Fill in to load only date from datetime:
datetime import date