Course contentsLesson 12 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 12

Modules and the standard library

Edit lesson

Import reusable code and use a module from Python's standard library.

14 minProgress saves on this device
In this lesson
  • Import and use a module
  • Recognize standard-library modules
  • Understand why environments isolate dependencies

Helpful background: Understand functions and lists.

Import a module

A module is a file or built-in component that supplies names such as functions and constants. import makes the module available to your code.

The statistics module is included in Python's standard library. mean() returns the arithmetic mean of a non-empty collection.

Use a standard-library modulepython
import statistics

counts = [8, 12, 10]
print(statistics.mean(counts))  # 10

Use the module name

Writing statistics.mean makes the origin of mean clear. You can import a specific name with from statistics import mean, but avoid importing everything with a wildcard in beginner projects.

Avoid naming your own file statistics.py if you intend to import the standard-library module; a local file can shadow it.

Organize your own code

You can put related functions in a Python file and import that module from another file in the same project. Python searches for modules using its import path.

Modules are executed when first imported in a process. Use the common if __name__ == "__main__" guard for code that should run when a file is executed directly rather than imported.

Keep project dependencies separate

The standard library comes with Python. Third-party packages are installed separately. A virtual environment gives a project its own installed packages so different projects can use different versions.

Create and activate a virtual environment using the instructions for your operating system; do not commit its generated files to your repository.

Knowledge check

Where does the statistics module in the example come from?

Try first; feedback appears after you check.
Apply it

Your turn

Use statistics.mean() to find the average of 4, 6, and 8.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson