Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Modules & Imports

12 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 5 · View course roadmap
Step 1

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 mathmath.sqrt(16)
  • from math import sqrt, pisqrt(16) directly
  • import 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.py shadows 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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +25 XP

Blank · autosaved

Import math and print: the square root of 225, pi rounded to 2 decimals (use round), and math.ceil(4.2).

Target output
15.0
3.14
5
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does `if __name__ == "__main__":` check?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path