Modules and Packages
Import a module and use a function from Python's standard library.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
A module is a file of reusable Python code. import makes its names available through the module name, as in math.sqrt(). A package organizes related modules.
You can import a particular name with from ... import ..., or choose a short alias with as. For beginner code, keeping the module name visible often makes it easier to see where a function came from.
- import a module
- Use module.name
- Packages group modules
See it step by step
Read the code, predict the output, then compare it with the result.
01. Use math functions
import math
print(math.sqrt(49))
print(math.ceil(2.2))7.0
3The math module groups related functions. Use math.name to access a function after import.
02. Use a second module
import statistics
scores = [4, 8, 12]
print(statistics.mean(scores))8statistics is another standard library module. mean() calculates the average of the three numbers.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Add import random near import math. Save the result with roll = random.randint(1, 6), then print(roll). Each run may show a different whole number.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Using a module before importing it
print(math.sqrt(9))import math
print(math.sqrt(9))What happens: NameError if math has not been imported in this run.
Import the module before using its name.
Shadowing the module name
import math
math = 4
print(math.sqrt(9))import math
number = 4
print(math.sqrt(9))What happens: AttributeError because math now refers to the integer 4.
Avoid reusing an imported module's name for another value.