LESSON 12 · BEGINNER PATH10 min

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

PYTHON
import math
print(math.sqrt(49))
print(math.ceil(2.2))
EXPECTED OUTPUT
7.0
3

The math module groups related functions. Use math.name to access a function after import.

02. Use a second module

PYTHON
import statistics
scores = [4, 8, 12]
print(statistics.mean(scores))
EXPECTED OUTPUT
8

statistics 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 run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnImport the random module, store one random.randint(1, 6) result in roll, and print roll as a simulated die roll.
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.

    01.After import math, how do you call its square-root function?

    02.What does from math import sqrt let you write?

    03.What does a package primarily help organize?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Using a module before importing it

    COMMON MISTAKE
    print(math.sqrt(9))
    FIX
    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

    COMMON MISTAKE
    import math
    math = 4
    print(math.sqrt(9))
    FIX
    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.