Modules, Packages & the Standard Library
Reuse code that already exists: the ways to import, a tour of the most useful standard-library modules (math, random, datetime, collections, statistics, os and sys), installing outside packages, reading documentation, and splitting your own program into modules.
Modules: code in other files
A module is a Python file of functions and values you can reuse with import. Python comes with hundreds of ready-made modules, called the standard library ("batteries included"). Thousands more packages (folders of modules) can be installed with pip, such as pandas and scikit-learn. Before writing something yourself, it is worth checking whether a module already does it.
Four ways to import
| Code | Then you write | When to use it |
|---|---|---|
import math | math.sqrt(16) | the default: clear where each name comes from |
from math import sqrt, pi | sqrt(16) | a few names you use a lot |
import pandas as pd | pd.read_csv(…) | long names with a standard short alias (np, pd, plt) |
from math import * | sqrt(16) | avoid: you cannot tell where names come from, and they can overwrite yours |
Put imports at the top of the file. Importing the same module twice is harmless: Python loads it once.
math and statistics
import math
import statistics as st
print(math.sqrt(81), math.pi, math.floor(3.7), math.ceil(3.2))
print(math.isclose(0.1 + 0.2, 0.3)) # the safe way to compare decimals
print(math.log(100, 10), math.exp(1))
print(math.dist((0, 0), (3, 4))) # distance between two points: 5.0
waits = [12, 45, 8, 30, 62, 15, 5]
print(st.mean(waits), st.median(waits), round(st.stdev(waits), 1))random: chance and sampling
Random numbers drive games, simulations, and machine learning (shuffling data, splitting it, initialising models). Computer random numbers are pseudo-random: produced by a formula. Setting a seed makes them repeat exactly, which is essential when you want results others can reproduce.
import random
random.seed(42) # same seed, same "random" results every run
print(random.randint(1, 6)) # a dice roll: 1 to 6 inclusive
print(random.random()) # a float from 0 up to 1
print(random.choice(["tea", "coffee", "juice"]))
cards = list(range(1, 11))
random.shuffle(cards) # shuffles the list in place
print(cards)
print(random.sample(cards, 3)) # 3 different items
rolls = [random.randint(1, 6) for _ in range(6000)]
print("sixes:", rolls.count(6), "(about 1000 expected)")datetime: dates and times
Dates are trickier than they look (month lengths, leap years, time zones). The datetime module handles the arithmetic. Two methods do the conversions you need most: strptime parses text into a date, and strftime formats a date as text, both using codes like %Y (year), %m (month), %d (day).
from datetime import date, datetime, timedelta
d = date(2026, 11, 17)
print(d, d.year, d.strftime("%A %d %B %Y")) # Tuesday 17 November 2026
print(d + timedelta(days=30)) # 30 days later
due = date(2026, 12, 25)
print((due - d).days, "days to go")
t = datetime.strptime("17/11/2026 09:30", "%d/%m/%Y %H:%M") # text -> datetime
print(t, t.hour, t.weekday()) # weekday: Monday is 0
print(t.strftime("%Y-%m-%d")) # the safest format for data: 2026-11-17collections: better containers
The collections module has upgraded containers for common jobs: Counter counts things, defaultdict creates missing keys automatically (perfect for grouping), and namedtuple gives tuple items names.
from collections import Counter, defaultdict, namedtuple
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
orders = [("Sita", 30), ("Leo", 12), ("Sita", 18)]
by_customer = defaultdict(list) # a missing key starts as an empty list
for name, amount in orders:
by_customer[name].append(amount)
print(dict(by_customer))
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y, p)os and sys: talking to the computer
os works with the operating system (environment variables, folders) and sys with Python itself (its version, the command-line arguments). For files and folders, prefer pathlib from the Files lesson.
import os
import sys
print(sys.version.split()[0]) # which Python is running
print(os.getcwd()) # the current working folder
print(os.environ.get("HOME", "not set")) # read an environment variable safely
print(sys.argv) # command-line arguments: ['script.py', ...] when run from a terminalInstalling and using outside packages
Packages that are not in the standard library are installed with pip into your project's virtual environment (see Set up Python), then imported like any module:
Popular packages you will meet: numpy (fast maths on arrays), pandas (tables), matplotlib and seaborn (charts), scikit-learn (machine learning), requests (download from the web), pytest (testing). The playground and this page already include NumPy, pandas, scikit-learn and Matplotlib.
Reading documentation
Nobody remembers every function. Professionals look things up constantly; being good at it is a skill. Three quick ways:
help(math.sqrt)prints the docstring.dir(math)lists everything a module contains.- The official docs at docs.python.org ↗ describe every standard-library module, with examples.
- This site's Python reference: every built-in function and string, list and dictionary method, each with a runnable example.
import math
help(math.floor)
print([name for name in dir(math) if not name.startswith("_")][:12])Your own modules and the main guard
As programs grow, split them into several files. Any .py file is a module: if helpers.py defines def clean(name):, then another file in the same folder can write from helpers import clean.
When Python runs a file directly, it sets the special variable __name__ to "__main__"; when the file is imported, __name__ is the module's name. So code under if __name__ == "__main__": runs only when the file is the program itself, not when it is imported. Every script you write should end this way.
Practice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Import random, set the seed to 1, then build rolls: a list of 10 dice rolls with random.randint(1, 6). Set sixes to how many rolls were 6.
Using datetime.date, set days_left to the number of days from 17 November 2026 to 25 December 2026, and weekday to the day name of 25 December 2026 (use strftime("%A")).
Use collections.Counter to set top2 to the two most common fruits in basket, as a list of (fruit, count) pairs.
Summary
Import modules to reuse code: import module is the clearest form. The standard library covers maths, randomness, dates, counting and the operating system; pip installs everything else. Look things up with help, dir and the docs, and organise your own code into modules with a main guard.
Key words
- module
- a .py file of reusable code
- package
- a folder of modules, often installed with pip
- standard library
- the modules that come with Python
- import
- make a module's code available
- alias
- a short name:
import numpy as np - seed
- a starting value that makes random numbers repeatable
__name__ == "__main__"- True only when the file is run directly
Common mistakes
- Naming your file
random.py,math.pyorpandas.py: Python imports your file instead of the real module. from module import *: names appear from nowhere and can overwrite yours.- ModuleNotFoundError for a package you installed: it went into a different environment (see Set up Python).
- Forgetting the seed and getting different results each run when you needed them repeatable.
- Code at the top level of a module running every time it is imported: put it under the main guard.
Quiz
1. After import math, how do you call the square root function?
2. Why set random.seed(42)?
3. Which module counts things in one line?
4. What does strptime do?
5. Code under if __name__ == "__main__": runs…