Python Modules & pip
A module is simply a .py file whose code you can reuse with import. Python ships with hundreds of modules (the standard library), and pip installs thousands more from PyPI. This lesson shows how to use both, and how to organise your own code into modules.
- The different import styles
- Create and import your own module
- What if __name__ == “__main__” means
- Install packages with pip in a virtual environment
Import a module
import mathprint(math.sqrt(81)) from math import pi, floorprint(round(pi, 4), floor(7.9)) import statistics as statsprint(stats.mean([4, 8, 15, 16, 23, 42]))9.0 3.1416 7 18
| Style | Use it as | When |
|---|---|---|
import math | math.sqrt() | Default; clear where names come from |
from math import sqrt | sqrt() | You use a few names often |
import numpy as np | np.array() | Long names with a standard alias |
from math import * | sqrt() | Avoid: hides where names come from |
Explore a module
import randomnames = [n for n in dir(random) if not n.startswith("_")]print(len(names) > 20)print("choice" in names, "shuffle" in names)print(random.choice.__doc__.splitlines()[0])True True True Choose a random element from a non-empty sequence.
Create your own module
Any .py file is a module. Save this as pricing.py:
TAX_RATE = 0.18 def with_tax(amount): return round(amount * (1 + TAX_RATE), 2) def discount(amount, percent): return round(amount * (1 - percent / 100), 2)Then import it from another file in the same folder:
import pricingfrom pricing import discount print(pricing.with_tax(1000))print(discount(1000, 15))print(pricing.TAX_RATE)1180.0 850.0 0.18
if __name__ == “__main__”
When a file is run directly, its __name__ is "__main__". When it is imported, __name__ is the module’s name. This lets a file be both a reusable module and a runnable script:
def greet(name): return f"Hello, {name}" print("__name__ is", __name__) if __name__ == "__main__": print(greet("from the command line"))__name__ is __main__ Hello, from the command line
import greeterprint(greeter.greet("from app.py"))__name__ is greeter Hello, from app.py
When app.py imports greeter, the top-level print runs with __name__ set to greeter, but the code under the if does not.
Packages
A package is a folder of modules. Import modules from it with dots:
myshop/ __init__.py pricing.py cart.pymain.py -> from myshop.pricing import with_taxThe standard library
| Module | Use it for |
|---|---|
os, pathlib, shutil | Files, folders and paths |
sys | Interpreter details, command-line arguments |
datetime, time | Dates, times and timers |
json, csv | Reading and writing data files |
re | Regular expressions |
collections, itertools | Extra containers and iterator tools |
random, math, statistics | Numbers |
logging | Log messages |
unittest | Testing (pytest is the popular third-party choice) |
Install packages with pip
pip downloads packages from PyPI. Always run it through the Python you are using: python -m pip install requests.
$ python -m pip --versionpip 26.2.2 from C:\Python3\Lib\site-packages\pip (python 3.15)Use a virtual environment
A virtual environment is a private folder of packages for one project, so different projects can use different versions. Create one and check that its Python is used:
$ python -m venv .venv$ .venv\Scripts\python -c "import sys; print(sys.prefix.endswith('.venv'))"TrueActivate it so python and pip use it automatically:
- Windows:
.venv\Scripts\activate - macOS and Linux:
source .venv/bin/activate
Then install and record your packages:
pip install requests pytestpip freeze > requirements.txtsaves the exact versionspip install -r requirements.txtrecreates them on another machine
Add .venv/ to .gitignore. Commit requirements.txt (or pyproject.toml) instead, so others can rebuild the environment.
Check your understanding
Quick quiz
1. What is a Python module?
A folder with modules is a package.
2. What is __name__ when a file is run directly?
It is the module name only when the file is imported.
3. Why use python -m pip instead of plain pip?
With several Pythons installed, pip may belong to a different one.
4. Which file lists a project’s packages for others to install?
pip freeze > requirements.txt creates it and pip install -r reads it.
Program Practice
49 Python OS Module Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python modules FAQ
What is the difference between a module and a package?
A module is one .py file. A package is a folder that groups modules (traditionally with an __init__.py file).
What does if __name__ == “__main__” do?
It runs the code below it only when the file is executed directly, not when it is imported by another file.
What is pip in Python?
pip is the package installer. It downloads packages from the Python Package Index (PyPI): python -m pip install package-name.
Why should I use a virtual environment?
It isolates each project’s packages, so upgrading a package for one project cannot break another, and requirements.txt stays accurate.