Modules & Imports
Lesson 4 of 5 · View course roadmap
Learn the idea
A module is simply a .py file whose functions you can use elsewhere. Importing keeps projects organised and unlocks Python's ecosystem:
import math→math.sqrt(16)from math import sqrt, pi→sqrt(16)directlyimport numpy as np— community-standard aliases- Avoid
from module import *— nobody can tell where names came from
The if __name__ == "__main__": idiom marks code that runs only when the file is executed directly, not when imported — every professional script has it.
Where you'll use this
pip's 500,000+ packages all arrive through import. Splitting a growing script into modules is the first act of software architecture you'll perform on any real project.
Common mistakes
- Naming your file after a stdlib module — a local
random.pyshadows the real one and breaks imports mysteriously. Never name files json.py, csv.py, math.py… from module import *— nobody (including you) can tell where names came from.- Circular imports: A imports B which imports A. Restructure shared code into a third module.
Pro tip
Standard import order (enforced by pro linters): stdlib first, third-party second, your own modules third — alphabetical within each group, one blank line between groups.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +25 XP
Import math and print: the square root of 225, pi rounded to 2 decimals (use round), and math.ceil(4.2).
15.0 3.14 5
round(math.pi, 2) gives 3.14.
import math print(math.sqrt(225)) print(round(math.pi, 2)) print(math.ceil(4.2))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.