Python Modules
A module is a file of Python code that other programs can use. Instead of writing everything yourself, you import a module and use its functions, classes and values. Python comes with a large standard library of modules for maths, dates, random numbers, files, text, data formats and much more, and every .py file you write is a module too.
Importing a module
import math
import random as rnd
from datetime import date
from statistics import mean, median
print(math.sqrt(144), math.pi)
print(date(2026, 10, 21).year)
print(mean([3, 5, 10]), median([3, 5, 10]))
print(rnd.__name__)12.0 3.141592653589793 2026 6 5 random
There are three forms. import math loads the module, and you use its contents with a dot: math.sqrt. import random as rnd gives the module a shorter name. from statistics import mean, median brings selected names straight into your program, so you can call mean without a prefix. Avoid from module import *, which brings in every name and makes it hard to see where a name came from.
Exploring a module
dir(module) lists the names a module offers, and help(math.sqrt) shows the documentation of one of them. In the interactive interpreter, try import math and then dir(math) to see all the maths functions.
Writing your own module
Any .py file is a module. Put functions in a file, say helpers.py, and import it from main.py in the same folder. The example below has two files; Try it in the editor opens both:
"""Small helpers for working with prices."""
TAX_RATE = 0.18
def with_tax(price):
return round(price * (1 + TAX_RATE), 2)
def rupees(amount):
return f"Rs {amount:,.2f}"import helpers
from helpers import rupees
price = 1500
print(rupees(helpers.with_tax(price)))
print("Tax rate:", helpers.TAX_RATE)python3 main.py
Rs 1,770.00 Tax rate: 0.18
The module's name is the file name without .py. Python looks for it first in the folder of the program you run, then in the standard library.
Code that runs only as a program
When a file is run directly, Python sets the variable __name__ to "__main__"; when it is imported, __name__ is the module's name. Putting test code under if __name__ == "__main__": makes it run only when the file is the program, not when another file imports it.
Practice exercises
- Import
mathand print the square root of 2 and the value ofmath.e. - Use
from random import choiceto pick a random item from a list. - Create a module
shapes.pywith functions for the area of a circle and of a square, and use it frommain.py. - Add an
if __name__ == "__main__":block toshapes.pythat tests its functions, and check that it does not run whenmain.pyimports the module.