Python Tutorial › Modules › Modules & pip

Python Modules & pip

IntermediateLesson 35 of 4712 min read6 runnable examples

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.

Advertisement
In this lesson
  • 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

Python
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]))
Output
9.0
3.1416 7
18
StyleUse it asWhen
import mathmath.sqrt()Default; clear where names come from
from math import sqrtsqrt()You use a few names often
import numpy as npnp.array()Long names with a standard alias
from math import *sqrt()Avoid: hides where names come from

Explore a module

Python
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])
Output
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:

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:

shop.py
import pricingfrom pricing import discount print(pricing.with_tax(1000))print(discount(1000, 15))print(pricing.TAX_RATE)
Output
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:

greeter.py
def greet(name):    return f"Hello, {name}" print("__name__ is", __name__) if __name__ == "__main__":    print(greet("from the command line"))
Output
__name__ is __main__
Hello, from the command line
app.py
import greeterprint(greeter.greet("from app.py"))
Output
__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:

Terminal
myshop/    __init__.py    pricing.py    cart.pymain.py          ->  from myshop.pricing import with_tax

The standard library

ModuleUse it for
os, pathlib, shutilFiles, folders and paths
sysInterpreter details, command-line arguments
datetime, timeDates, times and timers
json, csvReading and writing data files
reRegular expressions
collections, itertoolsExtra containers and iterator tools
random, math, statisticsNumbers
loggingLog messages
unittestTesting (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.

Terminal
$ 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:

Terminal
$ python -m venv .venv$ .venv\Scripts\python -c "import sys; print(sys.prefix.endswith('.venv'))"True

Activate 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 pytest
  • pip freeze > requirements.txt saves the exact versions
  • pip install -r requirements.txt recreates them on another machine
Tip

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?

2. What is __name__ when a file is run directly?

3. Why use python -m pip instead of plain pip?

4. Which file lists a project’s packages for others to install?

Program Practice

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.

Leave a Comment