Modules and imports
A module is a file of Python code that other programs can use. Python comes with hundreds of them, called the standard library: code for math, dates, files, random numbers and much more, already written and tested. You met one in lesson 3:
1import math2 3print(math.sqrt(16))4print(math.pi)5print(math.ceil(7 / 3))
4.0 3.141592653589793 3
import math loads the module once and gives you the name math. Everything inside is reached with a dot: math.sqrt, math.pi. Put your imports at the top of the file, so a reader can see at a glance what the program uses.
import
Import several modules on one line, like import math, statistics, or one per line (the more common style). Here statistics works out the usual averages of a list:
1import statistics2 3ore = [12, 7, 9, 12, 5]4print(statistics.mean(ore))5print(statistics.median(ore))6print(statistics.mode(ore))
9 9 12
| Function | Gives back |
|---|---|
mean | the average: the sum divided by how many |
median | the middle value once they are sorted |
mode | the value that appears most often |
The module name in front keeps things clear: statistics.mean cannot be confused with a mean function of your own.
from, import and as
from module import name brings just that name in, so you can use it without the module name and the dot. as gives a module or a name a shorter or clearer name.
1from math import sqrt, pi2import statistics as stats3import datetime as dt4 5print(sqrt(81))6print(round(pi, 2))7print(stats.mean([2, 4, 9]))8print(dt.date(2026, 11, 1))
9.0 3.14 5 2026-11-01
| Write | Then use |
|---|---|
import math | math.sqrt(9) |
from math import sqrt | sqrt(9) |
import statistics as stats | stats.mean(...) |
from math import * | every name in math, with no prefix; best avoided, since you can't see where a name came from |
What happens?
1import math2 3print(math.ceil(2.5))4print(ceil(4.2))
import math gives you the name math, not the names inside it. The first print works; the second meets the unknown name ceil and stops. Write math.ceil, or also from math import ceil.
A few handy modules
| Module | What it is for | Example |
|---|---|---|
random | random numbers and choices | random.randint(1, 6) |
statistics | averages and spread | statistics.median(xs) |
collections | extra containers: Counter, defaultdict, deque, namedtuple | Counter(words) |
string | ready-made strings of letters, digits, punctuation | string.digits |
time | the clock, and waiting | time.sleep(1) |
math | square roots, rounding up and down, pi | math.floor(2.7) |
random picks something different every time you run, so here we only check what kind of result it gives. Run it a few times; the output stays the same even though the numbers behind it change:
1import random2 3roll = random.randint(1, 6)4print(1 <= roll <= 6)5lamp = random.choice(["Elm", "Oak", "Mill"])6print(lamp in ["Elm", "Oak", "Mill"])7rolls = [random.randint(1, 6) for i in range(10)]8print(len(rolls))9print(min(rolls) >= 1 and max(rolls) <= 6)
True True 10 True
randint(a, b) gives a whole number from a to b, both included; choice picks one item from a list. The module has more, such as shuffle, which mixes up a list. collections has containers that save you work when counting and grouping:
1from collections import Counter, defaultdict2 3loads = ["ore", "oil", "ore", "wick", "ore", "oil"]4counts = Counter(loads)5print(counts["ore"])6print(counts.most_common(2))7 8by_letter = defaultdict(list)9for item in ["oak", "elm", "oil", "ash"]:10 by_letter[item[0]].append(item)11print(dict(by_letter))
3
[('ore', 3), ('oil', 2)]
{'o': ['oak', 'oil'], 'e': ['elm'], 'a': ['ash']}
A Counter counts for you, like the dictionary counting loop from lesson 11. A defaultdict(list) gives a new empty list for a key it has not seen, so you can append straight away. And string and time:
1import string2import time3 4print(string.ascii_uppercase)5print(string.digits)6code = "LAMP42"7print(all([c in string.ascii_uppercase + string.digits for c in code]))8 9start = time.time()10total = sum(range(100000))11print(time.time() - start >= 0)
ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 True True
time.time() is the number of seconds since 1970, so it changes every moment. Take it before and after some work, and the difference is how long the work took; lesson 25 does more with time. all([...]) gives True when every item in the list is true.
What's inside a module
On your own computer, Python's interactive mode (type python in a terminal) can tell you. dir() lists the names in a module, and help() shows what one of them does:
1import math2dir(math) # ['acos', 'ceil', 'floor', 'pi', 'sqrt', ...]3help(math.ceil) # ceil(x, /) Return the ceiling of x ...
These two don't work in the browser examples here. The other place to look is the official documentation at docs.python.org, which has a page for every module in the standard library.
Your own module
Any .py file is a module. Split a growing program into files, and import one from another by its file name without .py. Say you have these two files in the same folder on your computer:
1PRICE = 42 3def cost(count):4 return count * PRICE5 6def label(street):7 return street.upper() + " LAMPS"
1import lamps2from lamps import label3 4print(lamps.cost(3))5print(label("Elm Street"))
Run main.py, and Python finds lamps.py next to it, runs it once, and makes its names available:
$ python main.py 12 ELM STREET LAMPS
The examples on this page each run on their own, so they can't import a file of yours; try this on your computer. Don't name your file after a standard module (random.py, math.py): Python would import your file instead of the real one.
if __name__ == "__main__"
Every module has a variable called __name__. In the file you run, it is "__main__"; in a file that is imported, it is the module's name, such as "lamps". That lets a file do one thing when you run it and another when it is imported:
1def cost(count):2 return count * 43 4def main():5 print("Testing cost:", cost(3))6 7print(__name__)8if __name__ == "__main__":9 main()
__main__ Testing cost: 12
Run this file directly and main() runs. If main.py did import it instead, __name__ would be its module name, the if would be false, and only the functions would be defined, with no test output. So if __name__ == "__main__": holds the code that should run only when the file is the program itself.
Installing packages
Beyond the standard library, thousands of packages written by other people are on the Python Package Index (PyPI). On your computer, install one with pip in a terminal, not inside Python:
$ pip install requests Successfully installed requests
After that, import requests works like any other module. Some systems call it pip3, or python -m pip. Packages can't be installed in the browser examples here; everything this course uses is in the standard library.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Average and middle
✓Use the statistics module to print the mean and then the median of the lamp hours.
8 7
1hours = [6, 9, 7, 12, 6]Top two
✓Import Counter with from ... import, count the deliveries, and print the two most common, with their counts.
[('ore', 3), ('oil', 2)]1deliveries = ["oil", "ore", "wick", "ore", "oil", "ore", "glass"]Missing letters
✓Print, as one word, the letters of the alphabet that do not appear in sign, in alphabetical order. Use string.ascii_lowercase.
dg
1sign = "the quick brown fox jumps over the lazy cat"What you learned
import moduleloads a module; use its names with a dot, as inmath.sqrt.from module import namebrings in just that name;asrenames a module or a name.- The standard library has modules like
random,statistics,collections,stringandtime;dir(),help()and docs.python.org show what is inside. - Any
.pyfile is a module you can import by its name;if __name__ == "__main__":runs code only when the file is run directly. pip install name, in a terminal, installs packages from PyPI.