Modules & Imports
Organize code with modules and imports. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Mathematical ComponentsStudy 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
pythonimport math print(math.sqrt(16))
Importing specific items
pythonfrom math import sqrt, pi print(sqrt(16)) print(pi)
Aliases for readability
Aliases make long names easier to type.
pythonimport 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.
pythonif __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.
Mathematical Components
Resolve external systems extracting logic evaluating math constraints.
Randomizing Arrays
Generate sequences navigating conditional boundaries cleanly via `random`.
Data Tracing Limits
Leverage datetime arrays mapping specific structures tracking logic properties constraints.
Collections Logic Configurations
Parse dataset sequences tracking objects counting instances cleanly evaluating metrics efficiently leveraging defaults natively.
Alias Identifiers
Enforce restrictions processing modules executing isolated boundaries safely utilizing unique naming mapping metrics restrictions limits.