Python Import: How to Use Modules
What Is a Module in Python?
A module is a file of Python code that someone already wrote for you, full of ready-made functions. You bring it into your program with the import keyword, then use its functions with a dot: math.sqrt().
import math
print(math.sqrt(25))
print(math.pi)5.0 3.141592653589793
import math loads the math module. After that, math.sqrt(25) means "the sqrt function that lives inside math". It gives back the square root, 5.0.
Think of it like a toolbox in the garage. Python doesn't carry every tool around all the time. When you need a drill, you open the right toolbox first (import), then take out the drill (math.sqrt).
The rules
- Write
importand the module's name, usually at the very top of the file. - Use a function from it as
module.function(), with a dot in between. - Import a module once per program. Every line below can use it.
- Python comes with hundreds of modules, called the standard library. They are already installed: no download needed.
A few modules from the standard library
| Module | What it gives you | Example |
|---|---|---|
math | maths functions and numbers | math.sqrt(16) |
random | random numbers and picks | random.randint(1, 6) |
datetime | dates and times | datetime.date(2025, 3, 14) |
You'll meet all three in this chapter.
Avoid: using a module before you import it
print(math.sqrt(25))NameError: name 'math' is not defined
Don't be scared of this error! It's the same NameError you saw for a variable that doesn't exist. Python doesn't know the name math until you import it.
Common beginner doubt: "Are print() and len() from a module too?" They are built-in functions: Python always has them ready, with no import. Modules hold the extra tools you only need sometimes.
import a module once at the top, then use its tools with a dot: math.sqrt(25).