Modules and imports
Why this matters
Nobody writes AI software from scratch. The top of every AI script is a list of imports: json to read API replies, requests to call APIs, numpy for the math, the Anthropic SDK to talk to models. Once you know how imports work, and what Python's standard library already does, you reuse proven code instead of rewriting it. You can also read the first ten lines of any project and know what it depends on.
- Import a module, or specific names from it, and use what it provides
- Use the standard library for math, randomness, dates, statistics and counting
- Explain what a module is and where Python looks for one
- Avoid the import mistakes that confuse beginners
Borrowing code with import
Think of a toolbox you borrow from a neighbor. You don't build a drill from scratch; you borrow one that already works. A module is that toolbox: a file of Python code, full of functions and values, that you can load into your program. Python ships with hundreds of them, called the standard library. Here's the math module:
import math print(math.sqrt(144)) print(math.ceil(4.2)) print(math.floor(4.8)) print(math.pi)
import math loads the module once. It gives you a name, math, to reach inside it with a dot: math.sqrt, math.pi. The dot means "the thing called sqrt that lives in math".
ceil rounds up and floor rounds down. That matters when you're working out how many batches, pages or boxes you need.
Three ways to import
import statistics from math import floor, ceil import datetime as dt print(statistics.mean([12, 18, 21])) print(floor(7.9), ceil(7.1)) print(dt.date(2026, 11, 27).strftime("%A"))
import statisticsbrings in the whole module. You writestatistics.meanevery time, which makes it obvious wheremeancame from.from math import floor, ceilbrings in specific names, so you writefloor(...)directly.import datetime as dtgives the module a shorter alias. Some aliases are universal conventions you'll see in every data and AI project:import numpy as np,import pandas as pd.
You may also meet from math import *, which dumps every name from the module into your program. Avoid it. Readers can no longer tell where a name came from, and it can silently replace your own variables.