One of the biggest reasons people love Python is that you rarely have to start from scratch. Need random numbers, dates, maths functions or a way to download a web page? Someone has already written well-tested code for it, and you can use it with a single import line.
A module is simply a Python file containing functions, classes and variables. Python ships with a huge standard library of modules, and there are hundreds of thousands more packages on the Python Package Index (PyPI), which you install with a tool called pip. You can also split your own programs into modules to keep them organised.
In this lesson you'll import modules in different ways, meet some of the most useful standard library modules, write and import a module of your own, and install third-party packages safely inside a virtual environment.
Ways to import
import math
print(math.sqrt(16)) # use the module name as a prefix
from random import choice, randint
print(randint(1, 6)) # use the names directly
import datetime as dt
print(dt.date.today()) # a shorter aliasimport modulekeeps everything behind the module's name, which makes it clear where each function comes from.from module import namebrings in just the names you need.import module as aliasgives a long name a short nickname, as in the commonimport pandas as pd.
Avoid from module import *. It dumps every name into your program, and you can no longer tell where anything came from.
Useful standard library modules
| Module | What it gives you |
|---|---|
random | randint, choice, shuffle for games and sampling |
math | sqrt, pi, floor, ceil and more |
datetime | Dates, times and differences between them |
os and pathlib | Files, folders and paths |
json and csv | Reading and writing data files |
statistics | mean, median, mode |
collections | Counter for counting, and other handy containers |
The official documentation at docs.python.org describes every module. When you think "surely someone has solved this", check the standard library first.
Writing your own module
Any .py file can be imported by another file in the same folder. If helpers.py contains:
def format_price(amount):
return f"£{amount:.2f}"then another file can use it with from helpers import format_price. Splitting a program into modules keeps each file focused: one for data loading, one for calculations, one for output.
When a file is run directly, Python sets its special variable __name__ to "__main__". When it's imported, __name__ is the module's name. That's why you'll often see:
if __name__ == "__main__":
main()Code inside this block runs only when you execute the file itself, not when another file imports it.
Packages and how Python finds modules
When a project grows beyond a few files, group related modules into a package: a folder of modules, usually with an __init__.py file inside it.
shop/
__init__.py
pricing.py
stock.py
main.pymain.py can then write from shop.pricing import add_vat or import shop.stock. The __init__.py file runs when the package is first imported and can be empty. (Python 3.3 and later also allow "namespace packages" without it, but an explicit __init__.py avoids surprises.)
When you write import something, Python searches a list of folders stored in sys.path. The first entry is the folder of the script you ran, followed by the standard library and the site-packages folder where pip installs packages. A module is executed only the first time it is imported; later imports reuse the already-loaded module, so top-level code in a module does not run twice.
pip and virtual environments
pip installs packages from PyPI: pip install requests. To avoid different projects fighting over package versions, create a virtual environment for each project, a private folder of packages:
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # macOS and Linux
pip install requests
pip freeze > requirements.txtOnce activated, your terminal prompt shows (.venv) and every pip install goes into that project only. requirements.txt lists the exact packages, so anyone can recreate the environment with pip install -r requirements.txt. Add .venv/ to your .gitignore rather than committing it.
Python Modules Syntax
Imports and environments
import module
from module import name1, name2
import long_module_name as short
if __name__ == "__main__":
main()python -m venv .venv
pip install package-name
pip install -r requirements.txtPython Modules Summary
- A module is a
.pyfile;importmakes its code available. import m,from m import nameandimport m as aliasare the main styles.- The standard library includes
random,math,datetime,json,csvand much more. if __name__ == "__main__":runs code only when the file is executed directly.- Use
pipinside a virtual environment, and record packages inrequirements.txt.
Python Modules Examples
Each example shows the code, the output it produces and what each part does.
A dice game with random
The numbers are random, so your output will differ. This is one possible run.
import random
rolls = [random.randint(1, 6) for _ in range(5)]
print("Rolls:", rolls)
print("Best roll:", max(rolls))
players = ["Ana", "Ben", "Cleo"]
random.shuffle(players)
print("Order:", players)
print("Winner:", random.choice(players))Rolls: [3, 6, 1, 4, 4]
Best roll: 6
Order: ['Cleo', 'Ana', 'Ben']
Winner: AnaLine-by-line explanation
- Line 3randint(1, 6) includes both 1 and 6. _ is a common name for a loop variable you don't use.
- Line 8shuffle() rearranges the list in place.
- Line 10choice() picks one random item. Call random.seed(1) first if you need the same results every run, for example when testing.
Dates with datetime
from datetime import date, timedelta
start = date(2024, 9, 2)
exam = date(2024, 12, 16)
days_left = (exam - start).days
reminder = exam - timedelta(weeks=1)
print(f"{days_left} days until the exam")
print("Reminder on:", reminder.strftime("%A %d %B"))105 days until the exam
Reminder on: Monday 09 DecemberLine-by-line explanation
- Line 6Subtracting two dates gives a timedelta; .days is the number of days.
- Line 7Subtract one week to set a reminder.
- Line 10strftime() formats a date: %A is the weekday, %d the day and %B the month name.
Your own module
Two files in the same folder:
# money.py
def format_price(amount, currency="£"):
return f"{currency}{amount:.2f}"
def add_tax(amount, rate=0.2):
return round(amount * (1 + rate), 2)
if __name__ == "__main__":
print("Testing:", format_price(add_tax(10)))# shop.py
from money import format_price, add_tax
for price in [4.5, 12, 0.99]:
print(format_price(add_tax(price)))£5.40
£14.40
£1.19Line-by-line explanation
- Lines 8 to 9This test only runs when money.py itself is executed, not when shop.py imports it. shop.py imports just the two functions it needs, so its output is only the three prices.
Common Python Modules Mistakes
Calling a function without its module name
import math
print(sqrt(25)) # NameError: name 'sqrt' is not definedimport math
print(math.sqrt(25))Installing packages globally for every project
pip install requests flask pandas # into the system Pythonpython -m venv .venv
.venv\Scripts\activate
pip install requests flask pandasA file named after the module you import
# file saved as random.py
import random
print(random.randint(1, 6)) # AttributeError# file saved as dice_game.py
import random
print(random.randint(1, 6))Python Modules in Real Projects
Packages power real Python work
Almost every real project depends on packages: requests for calling web APIs, pandas and matplotlib for data analysis and charts, Django and Flask for websites, and pytest for testing. Each project keeps its own virtual environment and requirements.txt, so a teammate or a server can install exactly the same versions with one command.
Python Modules FAQ
What is the difference between a module, a package and a library?
A module is a single .py file. A package is a folder that groups modules together. "Library" is an informal word for any reusable collection of code, which might be one module or many packages, such as the standard library or pandas.
How do I fix ModuleNotFoundError: No module named ...?
Usually the package is installed in a different Python than the one running your code. Activate the project's virtual environment, then install with python -m pip install name, which guarantees pip belongs to the same interpreter. Also check the spelling, since the install name and import name can differ (pip install beautifulsoup4, then import bs4).
Should I use pip or python -m pip?
python -m pip is the safer habit. It runs pip for exactly the Python you name, which matters when several Python versions are installed. Plain pip works fine once the right virtual environment is active.
What does if __name__ == "__main__" do?
It runs the indented code only when the file is executed directly, for example python report.py. When another file imports report, that block is skipped. This lets one file work both as a reusable module and as a script.
Where can I learn more about pip and virtual environments?
The pip and virtual environments lesson covers creating, activating and rebuilding environments in more detail, and dependency management explains pinning versions for projects you share.
Python Modules Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the line so randint can be used directly.
random randint
print(randint(1, 10))
Which command installs a package from PyPI?
What does this print?
import math
print(math.ceil(4.1), math.floor(4.9))
What does if __name__ == "__main__": do?
Why use a virtual environment for each project?
Python Modules Quiz
5 questions to check what you learned.
What is a Python module?
- A type of loop
- A built-in data type
- A .py file containing code you can import
- An error message
What does
import pandas as pddo?- Imports pandas and lets you refer to it as pd
- Renames the pandas package on disk
- Installs pandas
- Imports only the pd function
What file is commonly used to list a project's packages?
- packages.py
- requirements.txt
- pip.json
- modules.cfg
Why should you avoid
from module import *?- It's slower to type
- It doesn't work in Python 3
- It only imports classes
- It imports every name, making it unclear where names come from and risking clashes
What is a virtual environment for?
- Running Python in the browser
- Making code run faster
- Keeping each project's installed packages separate
- Hiding your code