import and the Standard Library
Python comes with a standard library of ready-made modules for dice rolls, dates, averages and more, and an import line brings one into your program, whole, by its names, or under a shorter name.
Apprentice · Python · Updated
After this lesson you can
- Bring a module into a program with import, from … import or import … as, and call the names it holds
- Choose a standard library module for a job, such as math, random, datetime or statistics, and repeat random results with a seed
Key takeaways
- A module is a file of Python code that another program can use, and the standard library is the set of modules that comes with Python.
- import random brings in the whole module, so you write random.randint(1, 6). from random import randint brings in only that name, so you write randint(1, 6).
- import statistics as stats gives a module a shorter name for this file, and stats.mean() then means statistics.mean().
- math, random, datetime and statistics cover rounding up, chance, dates and averages, so you don't write those yourself.
- random.seed(7), or a random.Random(7) of your own, makes the same random numbers come out on every run, which is what tests need.
Rolling dice, picking who goes first, finding next Friday's date, averaging a list of scores: programs need these all the time, and nobody writes them from scratch. Python comes with them ready-made, and one line, import, brings them into your program. You'll write that line at the top of almost every file from now on; the tests in every exercise start with one.
The example is Game Night: a group of friends who meet on Fridays to play board games, and the small program that rolls their dice and keeps their scores.
A die you can't write yourself
Game night has lost its dice, so the program has to roll them. Here's a first try with what you know so far:
die = [1, 2, 3, 4, 5, 6]
print("You rolled", die[2])
You rolled 3
It rolls a 3, and it will roll a 3 every time, because every line you've written does the same thing on every run. Picking a number nobody can predict is hard work, and Python's makers already did it, in a module: a file of Python code that other programs can use.
Think of a shared toolbox in a garage. When you need a hammer, you don't forge one; you open the toolbox. import (read "import", or "bring in") opens it:
import random
roll = random.randint(1, 6)
print("You rolled", roll)
random.randint(1, 6) is read "random dot randint": the randint function that lives inside the random module. It gives a whole number from 1 to 6, both ends included. Saved as dice.py and run three times, it printed this (yours will be different):
You rolled 5
You rolled 6
You rolled 2
Three ways to write an import
import random brings in the whole module, and every use names it: random.randint, random.choice. You can always see where a name came from.
from random import randint, choice brings in only the names you list, and you write them on their own. import statistics as stats brings in a module under a shorter name, for this file only. Here are both:
from random import choice, randint
import statistics as stats
players = ["Ana", "Ben", "Cleo", "Dev"]
print(choice(players), "goes first")
print("Dice:", randint(1, 6), randint(1, 6))
print("Average score:", stats.mean([12, 15, 9]))
One run printed:
Dev goes first
Dice: 6 3
Average score: 12
choice picks one item from a list. Mixing the styles up is a common slip: after from random import randint, the name random was never brought in, so random.randint(1, 6) stops with NameError: name 'random' is not defined. Did you forget to import 'random'?. Write the name the way you imported it.
Put imports at the top of the file, one module per line, so a reader sees at a glance what the program uses.
A short tour of the standard library
The standard library is the set of modules that comes with Python: close to 200 of them, installed with Python itself, nothing to download. Four cover most of what game night needs:
import math
import statistics
from datetime import date, timedelta
slices = 10 * 3
print("Pizzas to order:", math.ceil(slices / 8))
scores = [12, 15, 9, 15, 11]
print("Average score:", statistics.mean(scores))
print("Middle score:", statistics.median(scores))
game_night = date(2026, 11, 20)
print("Next game night:", game_night + timedelta(days=7))
Pizzas to order: 4
Average score: 12.4
Middle score: 12
Next game night: 2026-11-27
math.ceil(read "ceiling") rounds up to a whole number: 10 players eating 3 slices each need 30 slices, which is 3.75 pizzas of 8 slices, and nobody sells three quarters of a pizza, so 4.statistics.meanis the average, andstatistics.medianthe middle score once they're sorted.datetimeholdsdate(a calendar day) andtimedelta(a length of time). A date plustimedelta(days=7)is a week later.date.today()gives today's date, which changes every day, so it isn't printed here.
The same dice every time, for tests
Random rolls are what a game wants and what a test can't check: if the answer changes every run, what should the test expect? Python's random numbers come from a formula, and the formula starts from a number called the seed. Give it the same seed, and the same numbers come out:
import random
random.seed(7)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
random.seed(7)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
3 2 4
3 2 4
random.Random(7) makes a generator of your own with its own seed, a separate set of dice that nothing else in the program touches. A function that takes one as a parameter rolls real dice in a game and repeatable dice in a test:
import random
ben_dice = random.Random(7)
cleo_dice = random.Random(7)
print("Ben:", ben_dice.randint(1, 6), ben_dice.randint(1, 6))
print("Cleo:", cleo_dice.randint(1, 6), cleo_dice.randint(1, 6))
Ben: 3 2
Cleo: 3 2
Do it: work out how many tables game night needs
Game night's host sets up folding tables before everyone arrives. Every player needs a seat, and a table that's only partly full still has to be set up.
players: how many people are coming.seats: how many people fit at one table.
Your job: write the function tables_needed(players, seats) so it returns how many tables to set up.
- Divide the players by the seats, and round up to a whole number with the
mathmodule'sceilfunction. Importmathat the top of the file. - It returns a whole number (an
int), never a decimal such as2.5. - With no players, it returns
0.
Worked through: with tables_needed(10, 4), 10 ÷ 4 = 2.5 tables. Two tables seat only 8, so the host sets up 3.
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
The standard library is a toolbox you already own: before you write a tricky piece of code, look for the module that does it, and bring it in with one import line.