Modules and Imports
import, from-import, and your own modules.
4 minute read
Big idea
A module is a file of Python code you can reuse. import brings a module into your program so you can use its functions.
import
import math
print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7), math.ceil(3.2))output
4.0
3.141592653589793
3 4Run and edit it in the app.
import math gives you the name math; everything inside is reached with a dot: math.sqrt, math.pi. The dot keeps names organised — math.floor can't clash with a floor of your own.
Other ways to import
from math import sqrt, pi # just these names, used without "math."
import statistics as stats # a shorter nickname
from math import sqrt
import statistics as st
print(sqrt(81))
print(st.mean([2, 4, 9]))
print(st.median([5, 1, 3]))What does it print? Show the answer
9.0
5
3Run and edit it in the app.
Avoid from math import * — it dumps every name into your program, and you can no longer tell where a name came from.
Your own modules
Any .py file is a module. If you have helpers.py next to your program:
# helpers.py
def greet(name):
return f"Hello, {name}!"
then in main.py:
import helpers
print(helpers.greet("Ada"))
if __name__ == "__main__"
When Python imports a file, it runs it. To have code that runs only when the file is run directly — not when it's imported — use this guard:
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("test")) # only when you run helpers.py itself
__name__ is "__main__" in the file you ran, and the module's name in a file that was imported.
Installing more
Python ships with a huge standard library (next lesson). Thousands more packages — like requests for the web or numpy for maths — are installed from the terminal with pip install requests. (The exercises here use only the standard library.)
print(math.sqrt(49))output
7.0Run and edit it in the app.
After import random, how do you call its randint function?
Watch it
Think of it like
A toolbox in the garage. import math brings the whole toolbox into the room; from math import sqrt brings just the one tool you need.
Key terms
- Module — A
.pyfile whose code you can import. - import — Load a module so you can use its names.
- Package — A folder of modules; installed with
pip.
Check yourself
After from math import sqrt, how do you call it?
What is a module?
When is __name__ equal to "__main__"?