Modules & Packages
Organizing code across files, the standard library, and installing third-party packages.
A module is just a .py file — anything you define in it (functions, classes, variables) can be imported elsewhere. A package is a folder of modules with an __init__.py file marking it as importable.
python
# math_utils.py
def add(a, b):
return a + b
PI = 3.14159python
# main.py
import math_utils
print(math_utils.add(2, 3))
print(math_utils.PI)
from math_utils import add # import a specific name directly
print(add(2, 3))
import math_utils as mu # alias, common for long/library names
print(mu.add(2, 3))The Python standard library
Python ships with a large "batteries included" standard library — you don't install anything to use these:
python
import math
print(math.sqrt(16), math.pi)
import random
print(random.randint(1, 100)) # random int, inclusive both ends
print(random.choice(["Intro", "Loops", "Functions"]))
from datetime import date
print(date.today())Third-party packages with pip
For anything beyond the standard library — like requests for HTTP calls, or numpy for numerical arrays — you install with pip, Python's package manager, from the terminal (not inside your script):
bash
pip install requestspython
import requests
response = requests.get("https://api.github.com")
print(response.status_code)It's standard practice to install packages inside a virtual environment (python -m venv venv) per project, so different projects' dependencies don't collide with each other on your system.
if __name__ == "__main__":
This guard lets a file work both as a standalone script and as an importable module — code inside it only runs when the file is executed directly, not when it's imported elsewhere.
python
def main():
print("Running as a script")
if __name__ == "__main__":
main()Key points to remember
- A module is a .py file; a package is a folder of modules with an __init__.py.
- import x gives you x.name; from x import name imports it directly; import x as y aliases it.
- The standard library (math, random, datetime, os, json, ...) ships with Python — no install needed.
- pip installs third-party packages from the terminal, ideally inside a per-project virtual environment.
- if __name__ == "__main__": guards code that should only run when the file is executed directly, not when imported.
Try it yourself
Standard library modules in action
Revision Flashcards
Tap a card to flip it and see the answer.
