Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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__)
Output
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:

Example (2 files)Try it in the editor
helpers.py
"""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}"
main.py
import helpers
from helpers import rupees

price = 1500
print(rupees(helpers.with_tax(price)))
print("Tax rate:", helpers.TAX_RATE)
Command
python3 main.py
Output
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

  1. Import math and print the square root of 2 and the value of math.e.
  2. Use from random import choice to pick a random item from a list.
  3. Create a module shapes.py with functions for the area of a circle and of a square, and use it from main.py.
  4. Add an if __name__ == "__main__": block to shapes.py that tests its functions, and check that it does not run when main.py imports the module.