IntermediateLesson firstCategory 13 of 20

Modules & Imports

Organize code with modules and imports. Read the lesson first, then move through the exercises in order.

9 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Mathematical Components

Study Material

Read the full lesson

What a module is

A module is a Python file that contains code you can reuse. When you import a module, you can use its functions and variables.

Importing a module

python
import math print(math.sqrt(16))

Importing specific items

python
from math import sqrt, pi print(sqrt(16)) print(pi)

Aliases for readability

Aliases make long names easier to type.

python
import statistics as stats print(stats.mean([1, 2, 3]))

The standard library

Python includes many useful modules, such as math, random, json, and datetime.

Where Python looks for modules

Python searches the current folder and its installed libraries. If you name your file the same as a module (like random.py), it can cause import errors.

The name guard

When a file is run directly, __name__ is "__main__". This lets you run code only when the file is executed, not when it is imported.

python
if __name__ == "__main__": print("Run directly")

Common mistakes to avoid

  • Naming your file the same as a standard module.
  • Importing everything with from module import * (it hides where names come from).
  • Forgetting that imports happen at the top of the file.

What you should understand after this lesson

  • How to import modules and specific functions.
  • Why aliases are helpful.
  • How to avoid common import problems.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.