ASAmol Shukla
Projects
Courses
Prompts
Skills
Contact
Resume
Course Outline
Syllabus Overview

Complete Python Course: From Zero to Professional

Courses/Complete Python Course: From Zero to Professional/Lesson 15: Modules, Packages & Imports
40 mins lesson duration•8 mins read

Lesson 15: Modules, Packages & Imports

Organize code into files, import between them, use the __name__ guard, and install packages with pip.

Modules — Code in Files

A module is simply a .py file. Anything you can run, you can import: functions, classes, variables. When a file is imported, its top-level code runs once, and its names become available to the importer.

# math_helper.py
def square(x):
    return x ** 2
# main.py
import math_helper
print(math_helper.square(5))   # 25

Modules are how Python stays organized. Every library you pip install is ultimately a collection of modules — and your own projects should be too.

What You'll Learn in This Lesson

  • Import modules with all four import styles
  • Understand packages — folders of modules
  • Use the __name__ guard to make files both script + library
  • Install third-party packages with pip

Import Styles

Style Usage Example
import module module.name import math → math.sqrt(16)
from module import name name directly from math import sqrt → sqrt(16)
from module import a, b Several names from math import pi, sqrt
import module as m Alias import math as m → m.sqrt(16)

Which to use? import module keeps the namespace explicit (no name clashes). from module import name is shorter but can clash. Alias imports are great for long names like import matplotlib.pyplot as plt.

A warning on star imports: from module import * dumps every public name into your namespace — it can silently overwrite your variables and is banned in most professional style guides.


Packages — Folders of Modules

A package is a folder of modules containing an __init__.py file (even an empty one) that marks the folder as importable:

my_project/
├── __init__.py
├── main.py
└── utils/
    ├── __init__.py
    └── strings.py
from utils.strings import clean_text

Big projects are organized as packages — one folder per feature, modules inside.

The __init__.py file can be empty (just a marker) or it can pre-import convenient names so users write from utils import clean_text instead of the deeper path. In Python 3.3+, packages without __init__.py (namespace packages) also work — but explicit is better.


The name Guard — Script + Library in One File

if __name__ == "__main__": runs a block only when the file is executed directly, not when imported:

def square(x):
    return x ** 2

if __name__ == "__main__":
    # Runs only when: python math_helper.py
    print("square(5) =", square(5))
  • Direct run: __name__ is set to "__main__" → block runs.
  • Imported: __name__ is set to the module name → block skipped.

This lets every file be both a runnable script and a safe importable library.

Mental model: __name__ is a magic variable that answers "how was this file started?" If the answer is "as the main program", run the demo code. If "as a library", stay quiet and only offer the functions.


pip — The Package Installer

Third-party packages are installed with pip:

pip install requests
pip install numpy pandas matplotlib

Virtual environments keep each project's dependencies isolated — the professional standard:

python -m venv .venv        # create
source .venv/bin/activate   # activate (Windows: .venv\Scripts\activate)
pip install requests        # install into THIS project only

Never pip install globally — different projects need different versions.

Why virtual environments are non-negotiable in 2026:

  • Project A needs pandas 2.0; Project B needs pandas 1.5. Globally installed, they fight.
  • A corrupted global environment can break your whole machine's Python.
  • requirements.txt + venv = anyone can reproduce your exact environment: pip install -r requirements.txt.

Common Mistakes to Avoid

  • Mistake: Importing a module whose name shadows a built-in (e.g., math.py in your project) — Fix: rename your file.
  • Mistake: Circular imports (A imports B, B imports A) — Fix: move shared code to a third module or import inside functions.
  • Mistake: Putting executable code at module top level — Fix: wrap it in if __name__ == "__main__":.
  • Mistake: from module import * polluting the namespace — Fix: import explicitly or by module name.
  • Mistake: Installing packages globally instead of in a venv — Fix: create and activate a virtual environment per project.

Professional Tips & Tricks

  • Import at the top of the file, one import per line, in a consistent order (stdlib, third-party, local).
  • Always guard executable code with if __name__ == '__main__': so it can be imported safely.
  • Use relative imports (from . import utils) inside packages.
  • Freeze your dependencies with pip freeze > requirements.txt for reproducibility.
  • Alias long library names: import pandas as pd, import numpy as np.

Key Takeaways

  • A module is a .py file; a package is a folder of modules with __init__.py.
  • Four import styles: direct, from-import, multi-name, alias.
  • The __name__ guard makes files script + library.
  • pip install adds packages; virtual environments isolate them.
  • Keep imports at the top and guard executable code.

Next up: Module 5 — object-oriented programming with classes.

Interactive Lesson Code Snippet
# math_helper.py
def square(x):
    """Return x squared."""
    return x ** 2


def cube(x):
    """Return x cubed."""
    return x ** 3


if __name__ == "__main__":
    # Runs only when executed directly, not when imported
    print("Running math_helper directly")
    print("square(5) =", square(5))
Language: python

Lesson Code (Python)

# math_helper.py
def square(x):
    """Return x squared."""
    return x ** 2


def cube(x):
    """Return x cubed."""
    return x ** 3


if __name__ == "__main__":
    # Runs only when executed directly, not when imported
    print("Running math_helper directly")
    print("square(5) =", square(5))

Console Output

Running math_helper directly
square(5) = 25

Code Visualization Tips

  • 🧠Picture modules as library shelves: import pulls the right book (file) off the shelf.
  • 🧠Picture packages as shelves inside a room: folder -> modules -> names.
  • 🧠Trace the __name__ trick: direct run sets __name__ to '__main__'; import sets it to the module name.

Professional Tips & Tricks

  • ⚡Import at the top of the file, one import per line, in a consistent order (stdlib, third-party, local).
  • ⚡Always guard executable code with if __name__ == '__main__': so it can be imported safely.
  • ⚡Use relative imports (from . import utils) inside packages.

Python Code Judge & Practice Arena

LeetCode Style

Run real Python 3.12 WebAssembly code directly in your browser against automated test suites.

Solved:0 / 20
0 / 370 XP
Challenges:
Problem 1 of 20

Problem 1: Math Module Pipeline 1

Easy+10 XP
Write a function `math_pipeline_1(numbers)` using the math module to calculate the Euclidean norm (hypot) rounded to 2 decimal places.
Sample Test Cases:
Input: math_pipeline_1([3, 4])
Expected: 5.0
Input: math_pipeline_1([10])
Expected: 10.0
main.pyPython 3.12 (WASM)
1
2
3
4
5
6
7
8
9
10
11
12
Press Run Code to test or Submit to verify test cases

Test Your Knowledge

Instant feedback

Quick Check: Lesson 15: Python Modules, Packages, Virtual Environments & Pip

1 / 20
What does the `if __name__ == '__main__':` idiom ensure? # script.py def main(): print('Running standalone') if __name__ == '__main__': main()

Up next · Continue learning

Classes, Instances & Inheritance

Object structure, __init__ constructor, instance parameters, methods, and parent-child overrides.

10 mins read50 mins
Start next lesson
Previous: Scope, Closures & DecoratorsNext: Classes, Instances & Inheritance
Made withbyAmol Shukla·amolshukla.online
ASAmol Shukla

AI Developer, Trainer & Agentic AI Expert building practical learning systems and real-world AI applications.

Explore

  • Projects
  • Courses
  • Prompts
  • Skills
  • Contact
  • Experience
  • Blogs

Connect

  • Resume
  • Contact
© 2026 Amol Shukla·Created withbyamolshukla.online
Back to top