Home Course Roadmap
Lesson 34 · Modules & Packages 40–50 minutes Beginner

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.

Modules & Packages
Reading progress: 0%
01

Learning Objectives

By the end of this lesson, you will understand how Python modules work and how they help developers organize larger applications.

You will learn to:
  • 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.
02

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.

Think of a module as a toolbox.

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:

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.

03

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.
Example project
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.

04

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:

calculator.py
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.

05

Importing a Module

Use the import statement to import a module.

main.py
import calculator

result = calculator.add(10, 5)

print(result)
Output
15

Python loads the calculator module and makes its members available through the module name.

06

Accessing Module Members

After importing a module, use dot notation to access its functions, variables, or classes.

Example
import calculator

print(calculator.add(10, 20))
print(calculator.multiply(4, 5))
print(calculator.tax_rate)
Output
30
20
0.15

The dot tells Python that you want something belonging to the imported module.

07

from ... import

Instead of importing the entire module name, you can import specific members directly.

Example
from calculator import add

result = add(10, 5)

print(result)
Output
15
Important difference

With import calculator, you use calculator.add(). With from calculator import add, you can use add() directly.

08

Importing Multiple Members

You can import several members from the same module.

Example
from calculator import add, multiply

print(add(2, 3))
print(multiply(4, 5))
Output
5
20
09

Import Aliases with as

An alias gives an imported module a shorter or more convenient name.

Example
import calculator as calc

print(calc.add(10, 20))

Python developers frequently use aliases for modules with long names or commonly recognized short names.

Common examples
import math as m
import datetime as dt
10

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 functions
  • random — random values and selections
  • datetime — dates and times
  • os — operating-system interaction
  • sys — Python runtime information
  • json — JSON data handling
  • csv — CSV file handling
  • statistics — statistical calculations
Big advantage:

You do not need to write everything from scratch. Python's standard library already provides many useful tools.

11

The math Module

The math module provides many mathematical functions and constants.

Example
import math

print(math.sqrt(25))
print(math.ceil(4.2))
print(math.floor(4.9))
print(math.pi)
Output
5.0
5
4
3.141592653589793

Useful math functions

  • math.sqrt()
  • math.ceil()
  • math.floor()
  • math.pow()
  • math.factorial()
  • math.pi
12

The random Module

The random module provides tools for generating pseudo-random values and making random selections.

Random number
import random

number = random.randint(1, 10)

print(number)

The exact number will vary each time the program runs.

Random choice

Example
import random

colors = ["red", "blue", "green", "yellow"]

selected = random.choice(colors)

print(selected)
Security note

The random module is not designed for security-sensitive secrets. For security-sensitive random values, Python provides the secrets module.

13

The datetime Module

The datetime module provides classes for working with dates and times.

Example
from datetime import datetime

now = datetime.now()

print(now)

You can also format a date into a readable string.

Formatted date
from datetime import datetime

now = datetime.now()

formatted = now.strftime("%Y-%m-%d")

print(formatted)
Example output
2026-09-12

The actual date depends on when the program is executed.

14

The os Module

The os module allows Python programs to interact with parts of the operating system.

Current working directory

Example
import os

print(os.getcwd())

Listing files

Example
import os

files = os.listdir()

print(files)

The exact output depends on the files and folders in the current directory.

15

The sys Module

The sys module provides access to information and functionality related to the Python interpreter.

Python version

Example
import sys

print(sys.version)

This displays information about the Python version being used to execute the program.

16

Custom Modules Across Files

One of the most useful applications of modules is splitting a program into multiple files.

Step 1 — Create a module

shop_utils.py
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

main.py
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)
Output
Subtotal: 2000
Discount: 200.0
Final Total: 1800.0
Why this is useful

The shopping calculations can now be reused by multiple parts of an application without copying the same functions everywhere.

17

if __name__ == "__main__":

You will frequently see the following pattern in Python:

Example
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.

Why use this pattern?

It allows a file to contain reusable definitions while also having code that runs only when that file is executed directly.

Example

calculator.py
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.

18

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.

Example
import sys

print(sys.path)

The exact list depends on your Python installation and environment.

Avoid confusing file names

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.

19

Common Import Errors

Import problems are common when you are first working with multiple Python files.

ModuleNotFoundError

Example
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.

Example
from calculator import divide

If calculator.py does not contain divide, the import will fail.

20

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

text_utils.py
def clean_text(text):
    return text.strip().lower()


def word_count(text):
    return len(text.split())

Multiple programs can import and reuse these utilities.

21

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.

Professional habit:

Place your imports near the top of your Python file so readers can quickly see which modules the program depends on.

22

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.

23

Mini Challenge — Shop Utility Module

Build a small reusable module for an e-commerce application.

Your task:

Create shop_utils.py and main.py.

Requirements

  1. Create a function that calculates subtotal.
  2. Create a function that calculates discount.
  3. Create a function that calculates tax.
  4. Create a function that calculates final total.
  5. Import those functions into main.py.
  6. Display a professional-looking order summary.

Suggested structure

shop_project/
├── main.py
└── shop_utils.py

Example data

main.py
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.

Challenge goal:

Practice separating business logic from the main program. This is the foundation of modular application development.

24

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?

25

Lesson Summary

Modules allow Python developers to organize and reuse code across multiple files.

Key concepts from this lesson:
  • A module is a Python .py file.
  • Modules make programs easier to organize.
  • import module imports a module.
  • Dot notation accesses module members.
  • from module import item imports a specific member.
  • as creates an import alias.
  • Python provides many built-in modules.
  • math provides mathematical tools.
  • random provides pseudo-random functionality.
  • datetime handles dates and times.
  • os interacts with the operating system.
  • sys provides Python runtime information.
  • __name__ identifies how a module is being used.
  • sys.path shows 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.