Learning LibraryCore Coding LibraryTeens

Imports and modules in Python: use code you didn't write

Rounding up, bell curves, square roots: someone has already written and tested all of it. A one-line import puts that work at your fingertips.

The big idea

A module is a file of reusable code; import loads it so you can use its functions with dot notation.

See it in code

1The basics

import math loads the module. You then reach inside it with a dot: math.ceil is the ceil function that lives in math:

python
import math

exact = 12500 / 24
print("Exact:", exact)
print("Tees to sell:", math.ceil(exact))
Run it. Rounding a break-even up:
Exact: 520.8333333333334
Tees to sell: 521

math.ceil rounds up to the next whole number, which is what break-even needs. The math. prefix says exactly where the function came from.

2A step further

from ... import pulls specific names into your program, so you can use them without the prefix:

python
from math import ceil, floor

exact = 12500 / 24
print("Round up:", ceil(exact))
print("Round down:", floor(exact))
Run it. The same result, a shorter call:
Round up: 521
Round down: 520

Shorter calls, at the cost of some clarity: a reader meeting ceil(...) far down the file has to scroll up to learn where it's from. Both styles are common.

3At Evergreen

A program can import as many modules as it needs. Here math handles the break-even and random simulates one season of uncertain demand:

python
import math
import random

launch_costs = 12500
profit_per_tee = 24
tees_needed = math.ceil(launch_costs / profit_per_tee)

demand = round(random.gauss(800, 250))
print("Tees needed to break even:", tees_needed)
print("Demand this season:", demand)
print("Covered the launch costs?", demand >= tees_needed)
Run it. One simulated season (yours will differ):
Tees needed to break even: 521
Demand this season: 736
Covered the launch costs? True

Imports sit together at the top, so anyone opening the file sees its dependencies at a glance. random.gauss(800, 250) draws from a bell curve centered on 800.

The same idea, everywhere

Your own files are modules too. Functions you've written and trust can be collected in one place and imported wherever they're needed, which is how real projects grow without repeating themselves.

Try it yourself

Add from math import sqrt and print sqrt(250 ** 2). Then move the import random line below the line that uses it, and read the error you get.

The common mistake

Using a module before importing it. math.ceil(x) without import math raises NameError: name 'math' is not defined. Python only knows the names you've brought in.

What it unlocks

Two modules get articles of their own: the math module for precise arithmetic, and random for simulation. What you import are functions like the ones you write.

Want the simpler version? Read the Kids version →