Modules
Python ships with a huge standard library: modules of ready-made tools. Bring one in with import:
import random random.choice(["a", "b"])
from math import sqrt # import one name import statistics as st # nickname
Use a module's tools with a dot, such as statistics.mean(data). For a list of numbers, mean gives the arithmetic average, median the middle value after sorting (or the average of the two middle values), and mode the most common value.
math.pi is the circle constant; a circle's area is pi * radius ** 2. math.ceil(x) rounds up to the smallest integer at least x.
random gives different results on every run. random.seed(7) fixes its starting point, so the same "random" results come back each time, which makes a program testable. random.randint(1, 6) picks a whole number from 1 to 6 inclusive.
statistics.pstdev(values) measures the spread of a complete population: the square root of the average squared distance from its mean. Unlike sample stdev, it accepts one reading and returns 0; neither accepts an empty list.
See it run
import math from datetime import date root = math.sqrt(81) launch = date(2025, 3, 14) print(root) print(launch.year, launch.month)
A module is a file of ready-made tools. import brings it in by name.
Practice modules
Exercise 1
Use the statistics module on the data list in the code editor below to set mean (5.6), median (7) and mode (7).
Exercise 2
Use math to summarize a circular table: radius = 3. Store area using pi and circumference using 2 pi radius. Store crates as the ceiling of 17 / 4: four items fit in a crate and a partial crate still counts.
Exercise 3
Use statistics in summarize(values). Return a dict containing mean, median, and population standard deviation under keys "mean", "median", "spread". Return None for an empty list; a single reading has spread 0. Leave the supplied list unchanged.
Exercise 4
Simulate dice for a board-game test. Import random and call random.seed(7) before rolling. Then build rolls: a list of 5 rolls from random.randint(1, 6), using a loop or a comprehension. Set total to their sum. Run it twice: thanks to the seed, the same five rolls appear every time.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.