A module is simply a Python file whose functions and variables you can use in another file. Python ships with hundreds of ready-made modules (the standard library), you can install thousands more with pip, and any .py file you write is already a module. This lesson covers the forms of import, a few essential standard modules, writing your own module, and what if __name__ == "__main__" means.
In this lesson you will learn
- The different ways to write an
import - Useful standard modules:
math,random,datetime,statistics - How to create and import your own module
- What
__name__ == "__main__"is for - How to install third-party packages with pip
Importing Standard Modules
import math
import random as rnd
from datetime import date
from statistics import mean, median
print(math.sqrt(81), math.pi)
print(round(math.pi, 2))
rnd.seed(7) # fixed seed so the output repeats
print(rnd.randint(1, 6))
print(date(2026, 12, 16).strftime("%d %B %Y"))
print(mean([70, 80, 90]), median([3, 1, 2]))
Output
9.0 3.141592653589793
3.14
3
16 December 2026
80 2
import mathloads the whole module; use its contents asmath.sqrt.import random as rndgives the module a shorter name.from datetime import datebrings one name in directly, so you can writedate(...).random.seed(7)makes the “random” numbers repeat. That is useful for testing, but leave it out in real programs.
Writing Your Own Module
Save this file as geometry.py:
"""geometry.py: a small module of our own."""
PI = 3.14159
def circle_area(r):
return PI * r * r
def _helper():
return "private by convention"
if __name__ == "__main__":
print("geometry.py run directly")
Then, in a second file in the same folder:
import geometry
from geometry import circle_area
print(geometry.PI)
print(circle_area(2))
print(geometry.__name__)
print([n for n in dir(geometry) if not n.startswith("__")])
Output of python main.py
3.14159
12.56636
geometry
['PI', '_helper', 'circle_area']
- The file name, without
.py, is the module name. if __name__ == "__main__":is true only when you rungeometry.pydirectly. When it is imported,__name__is"geometry", so the test line does not print. Use this block for demo or test code.- A leading underscore (
_helper) tells other programmers the name is meant for internal use. Python does not enforce it. dir(module)lists everything a module defines.
Packages and pip
A package is a folder of modules. Third-party packages are installed from the Python Package Index with pip, for example:
python -m pip install requests
After that, import requests works like any other module. Install packages for each project inside a virtual environment (python -m venv .venv) so projects do not clash.
Handy Standard Library Modules
| Module | Use it for |
|---|---|
math | Square roots, rounding, trigonometry, constants |
random | Random numbers, shuffling, choosing items |
datetime | Dates, times and differences between them |
os / pathlib | Files, folders and paths |
json / csv | Reading and writing data files |
collections | Counter, deque, defaultdict |
Common Mistakes
- Naming your file after a module, such as
random.pyormath.py. Your file is imported instead of the real one. from module import *. It hides where names come from and can overwrite your own variables.- Circular imports, where two modules import each other. Move the shared code into a third module.
- Installing with one Python and running with another.
python -m pipinstalls for the same Python you run.
Practice Exercises
Exercise 1. Print how many days remain until 31 December 2026 from 1 December 2026.
Show answer
from datetime import date
print((date(2026, 12, 31) - date(2026, 12, 1)).days) # 30
Exercise 2. Count letters in “banana” using a standard module.
Show answer
from collections import Counter
print(Counter("banana")) # Counter({'a': 3, 'n': 2, 'b': 1})
Frequently Asked Questions
What is the difference between a module and a package?
A module is a single .py file. A package is a folder that groups several modules together.
Where does Python look for modules?
First in the folder of the script being run, then in the standard library, then in installed packages. The full list is in sys.path.
Summary
- Any
.pyfile is a module;importlets another file use it. - Use
import x,import x as yorfrom x import name. if __name__ == "__main__":runs code only when the file is run directly.- Install third-party packages with
python -m pip install.
