Kodewick
Lesson 22 of 31Contents

Modules and imports

Lesson 22 of 31 · Part 4 · Code and data · about 20 minutes

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:

main.py
1import math2 3print(math.sqrt(16))4print(math.pi)5print(math.ceil(7 / 3))
Output
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:

main.py
1import statistics2 3ore = [12, 7, 9, 12, 5]4print(statistics.mean(ore))5print(statistics.median(ore))6print(statistics.mode(ore))
Output
9
9
12
FunctionGives back
meanthe average: the sum divided by how many
medianthe middle value once they are sorted
modethe 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.

main.py
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))
Output
9.0
3.14
5
2026-11-01
WriteThen use
import mathmath.sqrt(9)
from math import sqrtsqrt(9)
import statistics as statsstats.mean(...)
from math import *every name in math, with no prefix; best avoided, since you can't see where a name came from
Guess first

What happens?

1import math2 3print(math.ceil(2.5))4print(ceil(4.2))

A few handy modules

ModuleWhat it is forExample
randomrandom numbers and choicesrandom.randint(1, 6)
statisticsaverages and spreadstatistics.median(xs)
collectionsextra containers: Counter, defaultdict, deque, namedtupleCounter(words)
stringready-made strings of letters, digits, punctuationstring.digits
timethe clock, and waitingtime.sleep(1)
mathsquare roots, rounding up and down, pimath.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:

main.py
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)
Output
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:

main.py
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))
Output
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:

main.py
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)
Output
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:

lamps.py
1PRICE = 42 3def cost(count):4    return count * PRICE5 6def label(street):7    return street.upper() + " LAMPS"
main.py
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:

Terminal
$ 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:

main.py
1def cost(count):2    return count * 43 4def main():5    print("Testing cost:", cost(3))6 7print(__name__)8if __name__ == "__main__":9    main()
Output
__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:

Terminal
$ 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.

Exercise 1

Average and middle

Use the statistics module to print the mean and then the median of the lamp hours.

It should print
8
7
exercise1.py
1hours = [6, 9, 7, 12, 6]
Output
Press Run or Ctrl+Enter
Exercise 2

Top two

Import Counter with from ... import, count the deliveries, and print the two most common, with their counts.

It should print
[('ore', 3), ('oil', 2)]
exercise2.py
1deliveries = ["oil", "ore", "wick", "ore", "oil", "ore", "glass"]
Output
Press Run or Ctrl+Enter
Exercise 3

Missing letters

Print, as one word, the letters of the alphabet that do not appear in sign, in alphabetical order. Use string.ascii_lowercase.

It should print
dg
exercise3.py
1sign = "the quick brown fox jumps over the lazy cat"
Output
Press Run or Ctrl+Enter

What you learned

  • import module loads a module; use its names with a dot, as in math.sqrt.
  • from module import name brings in just that name; as renames a module or a name.
  • The standard library has modules like random, statistics, collections, string and time; dir(), help() and docs.python.org show what is inside.
  • Any .py file 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.