Python Modules
Learn how to organize Python programs into reusable files, import existing functionality, use Python's built-in modules, and build your own reusable modules.
Learning Objectives
By the end of this lesson, you will understand how Python modules work and how they help developers organize larger applications.
- Understand what a Python module is.
- Create your own reusable modules.
- Import modules using different techniques.
- Use built-in Python modules.
- Use aliases with imports.
- Understand
__name__. - Understand Python's module search path.
- Avoid common import-related errors.
What Is a Module?
A module is simply a Python file containing code that can be reused by another Python program.
A Python module normally has a
.py extension.
Instead of putting every function, class, and piece of logic into one huge file, you can organize related functionality into separate Python files.
Example
Imagine you create a file called
calculator.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
This file is now a module that contains reusable functions.
Why Modules Matter
Modules become extremely important as Python programs grow. A small program may fit comfortably inside one file, but large applications can contain thousands of lines of code.
Modules help developers:
- Organize code logically.
- Reuse functions and classes.
- Reduce duplicate code.
- Make programs easier to maintain.
- Separate different responsibilities.
- Work on different parts of a project independently.
shop/
├── main.py
├── products.py
├── customers.py
├── payments.py
└── reports.py
Each file can handle a specific responsibility rather than
placing everything inside main.py.
Creating Your Own Module
Creating a module is very simple: create a normal Python file and place reusable code inside it.
For example, create:
calculator.py
Then add:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
tax_rate = 0.15
The functions and variable can now be imported by another Python file.
Importing a Module
Use the import statement to import a module.
import calculator
result = calculator.add(10, 5)
print(result)
15
Python loads the calculator module and makes
its members available through the module name.
Accessing Module Members
After importing a module, use dot notation to access its functions, variables, or classes.
import calculator
print(calculator.add(10, 20))
print(calculator.multiply(4, 5))
print(calculator.tax_rate)
30
20
0.15
The dot tells Python that you want something belonging to the imported module.
from ... import
Instead of importing the entire module name, you can import specific members directly.
from calculator import add
result = add(10, 5)
print(result)
15
With import calculator, you use
calculator.add().
With from calculator import add,
you can use add() directly.
Importing Multiple Members
You can import several members from the same module.
from calculator import add, multiply
print(add(2, 3))
print(multiply(4, 5))
5
20
Import Aliases with as
An alias gives an imported module a shorter or more convenient name.
import calculator as calc
print(calc.add(10, 20))
Python developers frequently use aliases for modules with long names or commonly recognized short names.
import math as m
import datetime as dt
Built-in Python Modules
Python comes with a large standard library containing modules that provide ready-to-use functionality.
Some useful modules include:
math— mathematical functionsrandom— random values and selectionsdatetime— dates and timesos— operating-system interactionsys— Python runtime informationjson— JSON data handlingcsv— CSV file handlingstatistics— statistical calculations
You do not need to write everything from scratch. Python's standard library already provides many useful tools.
The math Module
The math module provides many mathematical
functions and constants.
import math
print(math.sqrt(25))
print(math.ceil(4.2))
print(math.floor(4.9))
print(math.pi)
5.0
5
4
3.141592653589793
Useful math functions
math.sqrt()math.ceil()math.floor()math.pow()math.factorial()math.pi
The random Module
The random module provides tools for generating
pseudo-random values and making random selections.
import random
number = random.randint(1, 10)
print(number)
The exact number will vary each time the program runs.
Random choice
import random
colors = ["red", "blue", "green", "yellow"]
selected = random.choice(colors)
print(selected)
The random module is not designed for
security-sensitive secrets. For security-sensitive
random values, Python provides the
secrets module.
The datetime Module
The datetime module provides classes for
working with dates and times.
from datetime import datetime
now = datetime.now()
print(now)
You can also format a date into a readable string.
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d")
print(formatted)
2026-09-12
The actual date depends on when the program is executed.
The os Module
The os module allows Python programs to
interact with parts of the operating system.
Current working directory
import os
print(os.getcwd())
Listing files
import os
files = os.listdir()
print(files)
The exact output depends on the files and folders in the current directory.
The sys Module
The sys module provides access to information
and functionality related to the Python interpreter.
Python version
import sys
print(sys.version)
This displays information about the Python version being used to execute the program.
Custom Modules Across Files
One of the most useful applications of modules is splitting a program into multiple files.
Step 1 — Create a module
def calculate_subtotal(price, quantity):
return price * quantity
def calculate_discount(amount, rate):
return amount * rate
def calculate_final_total(amount, discount):
return amount - discount
Step 2 — Import the module
import shop_utils
subtotal = shop_utils.calculate_subtotal(1000, 2)
discount = shop_utils.calculate_discount(
subtotal,
0.10
)
total = shop_utils.calculate_final_total(
subtotal,
discount
)
print("Subtotal:", subtotal)
print("Discount:", discount)
print("Final Total:", total)
Subtotal: 2000
Discount: 200.0
Final Total: 1800.0
The shopping calculations can now be reused by multiple parts of an application without copying the same functions everywhere.
if __name__ == "__main__":
You will frequently see the following pattern in Python:
def greet():
print("Hello from Python!")
if __name__ == "__main__":
greet()
What does __name__ mean?
Every Python module has a special variable called
__name__.
When a Python file is executed directly,
__name__ becomes:
"__main__"
When the same file is imported as a module,
__name__ contains the module's name instead.
It allows a file to contain reusable definitions while also having code that runs only when that file is executed directly.
Example
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(10, 5))
If you run calculator.py directly, it prints
15.
If another file imports calculator, the test
print statement does not execute automatically.
Module Search Path and sys.path
When Python encounters an import statement, it needs to determine where the requested module is located.
Python searches locations listed in its module search path.
This information can be inspected using sys.path.
import sys
print(sys.path)
The exact list depends on your Python installation and environment.
Do not name your own files after standard-library
modules such as random.py,
math.py, or datetime.py.
Doing so can cause confusing import behavior.
Common Import Errors
Import problems are common when you are first working with multiple Python files.
ModuleNotFoundError
import unknown_module
If Python cannot locate the module, it may raise:
ModuleNotFoundError
ImportError
An ImportError can occur when Python finds the
module but cannot import the requested item.
from calculator import divide
If calculator.py does not contain
divide, the import will fail.
Practical Real-World Examples
Modules are not just a theoretical concept. They are used constantly in professional Python development.
Example 1 — E-commerce Application
ecommerce/
├── main.py
├── products.py
├── customers.py
├── cart.py
├── payments.py
└── reports.py
Each module handles a different responsibility.
Example 2 — Data Analysis Project
analytics/
├── main.py
├── data_loader.py
├── cleaning.py
├── calculations.py
├── charts.py
└── reports.py
This makes the project easier to understand and maintain.
Example 3 — Reusable Utility Module
def clean_text(text):
return text.strip().lower()
def word_count(text):
return len(text.split())
Multiple programs can import and reuse these utilities.
Common Mistakes
1. Forgetting the import
You cannot normally use a module's functions before importing the module.
2. Incorrect module name
Make sure the module name matches the Python file name.
3. Importing a member that does not exist
If you write
from calculator import divide,
divide must actually exist in the
module.
4. Using wildcard imports
Avoid relying on
from module import *.
It can make code difficult to understand because
the source of names becomes unclear.
5. Naming conflicts
Avoid naming your own files after standard-library
modules such as random.py.
Place your imports near the top of your Python file so readers can quickly see which modules the program depends on.
Practice Exercises
Try these exercises yourself before looking for a solution.
Exercise 1 — Math
Import the math module and calculate the
square root of 144.
Exercise 2 — Random
Import random and generate a random number
between 1 and 100.
Exercise 3 — Date
Use datetime to display today's date.
Exercise 4 — Custom Module
Create a module called calculator.py
containing functions for addition and subtraction.
Exercise 5 — Import Specific Functions
Import only the add() function from your
calculator module.
Exercise 6 — Alias
Import math using the alias
m and calculate m.sqrt(81).
Exercise 7 — OS
Use the os module to display the current
working directory.
Mini Challenge — Shop Utility Module
Build a small reusable module for an e-commerce application.
Create shop_utils.py and
main.py.
Requirements
- Create a function that calculates subtotal.
- Create a function that calculates discount.
- Create a function that calculates tax.
- Create a function that calculates final total.
- Import those functions into
main.py. - Display a professional-looking order summary.
Suggested structure
shop_project/
├── main.py
└── shop_utils.py
Example data
price = 2500
quantity = 3
discount_rate = 0.10
tax_rate = 0.15
Your program should calculate the subtotal, discount, tax,
and final amount using functions imported from
shop_utils.py.
Practice separating business logic from the main program. This is the foundation of modular application development.
Quick Knowledge Check
Test your understanding of Python modules.
1. What is a Python module?
2. Which statement imports the math module?
3. How do you access a function from an imported module?
4. What does from math import sqrt do?
5. What does as do in an import?
6. Which module is commonly used for random selections?
7. What is the value of __name__ when a file is run directly?
8. Which module provides access to operating-system functionality?
9. What can sys.path help you understand?
10. Why should wildcard imports generally be avoided?
Lesson Summary
Modules allow Python developers to organize and reuse code across multiple files.
- A module is a Python
.pyfile. - Modules make programs easier to organize.
import moduleimports a module.- Dot notation accesses module members.
from module import itemimports a specific member.ascreates an import alias.- Python provides many built-in modules.
mathprovides mathematical tools.randomprovides pseudo-random functionality.datetimehandles dates and times.osinteracts with the operating system.sysprovides Python runtime information.__name__identifies how a module is being used.sys.pathshows module search locations.- Good modules separate responsibilities and promote reuse.
You are now ready to move from individual Python files into the next level of organization: packages.
Ready for the Next Lesson?
Make sure you understand imports, built-in modules,
custom modules, and __name__ before continuing.