Modules and Packages
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.
Import a module and use a function from Python's standard library.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Modules and Packages
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
You do not have to write every useful operation from scratch. Python's standard library gives you modules for mathematical calculations, statistics, dates, text processing, and many other jobs. A module is a file that groups related Python definitions. A package organizes modules under a shared name, often as a directory structure. Importing makes selected names available in your program. In this lesson we will calculate a circle's area with math, use statistics for a mean, and follow a package path to a URL query builder. We will also look at how your own code can become a module and why naming collisions cause confusing errors.
- 00:42
At the end, you will import random to simulate one die roll. Do not worry about memorizing every module name. The skill is to read an import, understand where a function comes from, and check the output against the job you intended. The first line imports math, a standard library module. That gives us the name math in this file. A dot then selects a name provided by that module. In the area calculation, math.pi provides an approximation of pi, radius to the power of two gives nine, and multiplication produces the area. The formatting expression displays the result with two digits after the decimal point, so you see Area: twenty-eight point twenty-seven.
- 01:26
The next print calls math.sqrt with eighty-one. The square root is nine, and math.sqrt returns a floating-point number, so it displays as nine point zero. Compare that with the lesson's smaller math example: sqrt of forty-nine displays seven point zero, while ceil of two point two displays the integer three. Different functions have different return types, even when their values look related. Import statistics next. The mean of four, five, six, and seven is five point five. math.ceil rounds that mean upward to six. By keeping the names statistics.mean and math.ceil, the code tells the reader which tool performed each step.
- 02:08
An alternative import style can bring a single name directly into the file, but the dotted form often makes provenance clearer for beginners. Packages extend the dotted path. In the lesson's query example, from urllib.parse import urlencode reaches the parse module inside the urllib package and imports the urlencode function. Pass it a dictionary with topic equal to python loops and level equal to basic, and it produces a query string where the space becomes a plus sign and pairs are joined with an ampersand. This is an example of letting a standard library function handle details that are easy to get wrong by hand.
- 02:48
Your own reusable code can work the same way. Imagine a file named shapes.py with a function for a rectangle's area, and a separate app.py file that says import shapes. If both files are in an importable location, app.py can call shapes.rectangle_area. Changing the function in shapes.py then helps every caller using that shared code. A module is not an extra kind of program; it is a way to give related definitions a home and make them reusable. Be aware that a module can execute top-level statements when first imported in a process, so keep unrelated demonstration prints behind a main guard in reusable files.
- 03:31
Finally, import random and call random.randint with one and six. The return value is an integer from one through six, including both endpoints. Unlike the previous examples, its exact output can vary between runs. You should check that the result is in range, not demand a particular face on every roll. Pause and decide which of these examples has a deterministic output and which does not before running them. A common first error is calling math.sqrt before the name math has been imported in that run. Python raises NameError because it does not know what math refers to. Add import math near the top and rerun the whole program.
- 04:13
Do not rely on an earlier interactive run that happened to import it; a complete script should include its own imports. The second error is more subtle. If you import math and then assign the integer four to the name math, that name now refers to four. Calling math.sqrt raises AttributeError because an integer has no sqrt attribute. The module still exists, but you replaced the local name that pointed to it. Rename the number variable and rerun. A third source of confusion is giving your own file the same name as a standard library module. A local math.py or random.py may be imported instead of the library module, leading to unexpected behavior.
- 04:59
Choose specific names for your files. When an import seems wrong, read the traceback and inspect which file Python actually imported rather than changing calls at random. Modules save work only when the names in your program still point where you think they do. Your practical task is to import random, call randint with one and six exactly once, save the result in roll, and print roll. Store it first so the displayed number is the same value your program generated, rather than calling randint twice and perhaps getting two different results. Run it several times. Every output should be an integer from one through six, but individual runs need not match.
- 05:42
Press Check Task to verify the code structure. As an extra exercise, return to math and print the square root of a perfect square of your choice. Predict both its mathematical value and the way Python displays its type. The quiz asks how to call a square-root function through math, what a direct import of sqrt allows, and what a package organizes. If you can explain where each name came from, you are ready to combine imported tools with user input in the next lesson.
Understand the concept
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.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Imports reveal where a calculation comes from
A standard library module gives you a focused set of tools without copying their implementations into your script. Keeping the module name in a call makes the dependency visible: statistics.mean calculates an average, while math.ceil rounds a number upward to an integer. Those operations serve different purposes, and their names tell a reader exactly which one is happening.
Import the modules once near the top, then use their names wherever needed below. A module does not automatically appear just because it ships with Python. Predict the result if the measurements change to [2, 3, 4, 5], then edit the list and compare the average with the rounded-up value. Notice that rounding up is not the same as ordinary rounding.
import math
import statistics
measurements = [4, 5, 6, 7]
average = statistics.mean(measurements)
print(average)
print(math.ceil(average))5.5
6- statistics.mean computes 22 divided by 4, which is 5.5.
- math.ceil gives the smallest integer at least as large as 5.5: 6.
A package path leads to a specific tool
The name urllib.parse has two levels: urllib is a package, and parse is one of its modules. The from form imports a particular tool from that module. This matters when a website builds a query string from user-facing values. Spaces and punctuation need encoding so that the resulting text can be used safely as part of a URL.
Here urlencode handles that encoding and joins two named parameters. The order follows the dictionary's insertion order, which makes the displayed result predictable in modern Python. In a real application, treat the result as a query string, not as an entire URL. Change 'python loops' to 'sets & tuples' and predict how the ampersand and spaces appear.
from urllib.parse import urlencode
query = {"topic": "python loops", "level": "basic"}
print(urlencode(query))topic=python+loops&level=basic- The import selects urlencode from urllib.parse.
- urlencode converts the space to + and separates parameters with &.
Move your own reusable code into a module
You can create a module yourself by saving functions in a Python file, such as prices.py. A second file in the same project can write import prices and call prices.total(...). That gives the calculation one home instead of copying it into every script. Keep code that should run only when a file is launched directly behind the familiar if __name__ == '__main__': guard.
When an import unexpectedly fails, first check the file name and the folder from which your program starts. Avoid naming your file after a standard library module such as random.py: Python may import your file instead of the module you intended. A package groups several related modules in a folder; you can adopt that layout after a single module becomes crowded. This two-file setup is best tried in a local editor because the lesson console runs one code cell at a time.
- Put reusable definitions in prices.py rather than duplicating them.
- Import that module from the script that needs it.
- Keep local file names distinct from standard library modules.
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.