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
import math loads the module. You then reach inside it with a dot: math.ceil is the ceil function that lives in math:
import math
exact = 12500 / 24
print("Exact:", exact)
print("Tees to sell:", math.ceil(exact))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.
from ... import pulls specific names into your program, so you can use them without the prefix:
from math import ceil, floor
exact = 12500 / 24
print("Round up:", ceil(exact))
print("Round down:", floor(exact))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.
A program can import as many modules as it needs. Here math handles the break-even and random simulates one season of uncertain demand:
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)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.
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.