Importing Modules
Use import, from...import, and aliases to bring code into your file
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Three ways to import
Python gives you three import styles. Each has a trade-off between clarity and convenience.
1. Import the whole module
import math
print(math.sqrt(16)) # 4.0You access functions with the module.function() syntax. This is the clearest style — every call shows where the function comes from. When you read math.sqrt(), you know instantly it belongs to the math module.
2. Import specific names
from math import sqrt, ceil
print(sqrt(16)) # 4.0
print(ceil(3.2)) # 4This pulls specific functions directly into your namespace. You call sqrt() instead of math.sqrt(). The code is shorter, but you lose the visual reminder of where the function lives.
Use this style when you call a function many times and the module name is obvious from context.
3. Import with an alias
import math as m
print(m.sqrt(16)) # 4.0An alias gives the module a shorter name. This is common with long module names. The data science community standardized on aliases like import numpy as np and import pandas as pd — you will see these everywhere.
Combining styles
You can mix import styles in one file. A common pattern imports the module for general use and pulls out one heavily-used function:
import os
from os.path import join
full_path = join("data", "report.csv")What not to do
Avoid from math import *. The star imports every name from the module into your namespace. If two modules define a function with the same name, the second import silently overwrites the first. Your code breaks with no warning.
from math import * # Imports everything — don't do this
from statistics import * # May overwrite names from mathExplicit imports make your code predictable.
Instructions
Practice the three import styles.
- Import the
mathmodule. Use the plainimportstatement. - Call
print()withmath.sqrt(25). - Import
ceilandfloorfrom themathmodule. Use thefrom ... importstyle. - Call
print()withceil(3.2). - Call
print()withfloor(3.8). - Import the
mathmodule with the aliasm. Useimport ... as. - Call
print()withm.pow(2, 10).
# Step 1: Import the math module # Step 2: Print math.sqrt(25) # Step 3: Import ceil and floor from math # Step 4: Print ceil(3.2) # Step 5: Print floor(3.8) # Step 6: Import math with alias m # Step 7: Print m.pow(2, 10)
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding