← All lessons
Python intermediate · Lesson 9 of 11

Modules and the standard library

A module is a file of Python code you can use from another file. import math loads the math module, and then math.sqrt(16) calls its sqrt function. from math import sqrt brings in just that name so you can write sqrt(16). import numpy as np gives a module a short nickname.

Python comes with hundreds of modules ready to use, called the standard library ("batteries included"). A few you'll use all the time:

import math
print(math.sqrt(81), math.pi > 3.14, math.ceil(4.1))

import random
roll = random.randint(1, 6)
print(1 <= roll <= 6)
coin = random.choice(["heads", "tails"])
print(coin in ("heads", "tails"))
Prints
9.0 True 5
True
True

random.randint(a, b) picks a whole number from a to b (both included), random.choice() picks an item, and random.shuffle() mixes a list. random.seed() makes the "random" sequence repeat, which helps when testing.

datetime handles dates and times, which are fiddlier than they look (months have different lengths, leap years, time zones). Subtracting two dates gives a timedelta, a length of time.

from datetime import date, timedelta

start = date(2026, 11, 25)
later = start + timedelta(days=10)
print(later)
print((date(2026, 12, 25) - start).days)
print(start.strftime("%d %B %Y"))
Prints
2026-12-05
30
25 November 2026

collections has handy containers. Counter counts things in one go, and defaultdict is a dict that makes a default value for a missing key, so grouping needs no get().

from collections import Counter, defaultdict

votes = ["tea", "coffee", "tea", "juice", "tea"]
print(Counter(votes).most_common(1))

by_letter = defaultdict(list)
for w in ["apple", "avocado", "banana"]:
    by_letter[w[0]].append(w)
print(dict(by_letter))
Prints
[('tea', 3)]
{'a': ['apple', 'avocado'], 'b': ['banana']}

Your own files are modules too. If helpers.py defines def tidy(s):, another file in the same folder can from helpers import tidy. Code at the top level of a module runs when it's imported, so scripts put their main work under if __name__ == "__main__":. That line is True only when the file is run directly, not when it's imported.

def tidy(s):
    return s.strip().lower()

if __name__ == "__main__":
    print(tidy("  Hello "))
Prints
hello

Beyond the standard library are hundreds of thousands of packages written by other people, on the Python Package Index (PyPI). You install them from the terminal with pip install requests, for example. The advanced course covers keeping each project's packages separate with a virtual environment.

Practice

What does this print?

import math
print(math.floor(7.9), math.ceil(7.1))
More info

Quick reference

import m / from m import x / import m as nLoad a module / one name from it / with a nickname.
mathsqrt, floor, ceil, pi and more.
randomrandint(a, b), choice, shuffle, seed.
datetimedate, datetime, timedelta, strftime for formatting.
collectionsCounter for counting, defaultdict for grouping.
if __name__ == "__main__":Code that runs only when the file is run directly.
pip install nameInstall a package from PyPI (in the terminal).

Related courses