Lesson 39 of 70 – Python Modules
56%

Python Modules

A module in Python is a file containing Python code such as functions, variables, classes, and statements. Modules help us organize code and reuse it in different programs.

Note: A Python module is usually a .py file that can be imported and used in another Python program.
What is a Module?

A module is a Python file that contains reusable code. Instead of writing the same code again and again, we can place it inside a module and import it whenever we need it.

For example, a file named:

calculator.py

can contain calculator functions that can be used by other Python programs.

Why Use Modules?
  • Modules help organize large programs.
  • They allow code reuse.
  • They make programs easier to maintain.
  • They reduce duplicate code.
  • They help separate different parts of an application.
  • Python provides many built-in modules.
Creating a Module

To create a module, simply create a Python file with the .py extension.

For example, create a file named:

calculator.py

Add the following code:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

The file calculator.py is now a module.

Importing a Module

We can use the import keyword to import a module.

import calculator

print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
Output:
15
5
The import Keyword

The import statement loads a module so that its contents can be used in the current program.

import math

print(math.sqrt(25))
Output:
5.0
Using Functions from a Module

After importing a module, we can access its functions using the dot operator.

import calculator

result = calculator.add(20, 30)

print(result)
Output:
50
Import Only Specific Functions

We can import a specific function from a module using from ... import.

from calculator import add

print(add(10, 20))
Output:
30

Now we can call add() directly without writing calculator.add().

Import Multiple Functions

We can import more than one function from a module.

from calculator import add, subtract

print(add(20, 10))
print(subtract(20, 10))
Output:
30
10
Import Everything from a Module

The * symbol can be used to import names from a module.

from calculator import *

print(add(5, 5))
print(subtract(10, 4))
Output:
10
6
Note: Using from module import * can make it less clear where a name came from. Explicit imports are generally easier to read.
Using an Alias for a Module

We can give a module a shorter name using the as keyword.

import math as m

print(m.sqrt(36))
Output:
6.0
Alias for a Function

We can also give an imported function another name.

from math import sqrt as square_root

print(square_root(49))
Output:
7.0
Built-in Python Modules

Python provides many modules as part of its standard library. Some commonly used modules are:

Module Purpose
math Mathematical functions
random Generate random values
datetime Work with dates and times
os Interact with the operating system
json Work with JSON data
re Regular expressions
The math Module

The math module provides many mathematical functions.

import math

print(math.sqrt(64))
print(math.factorial(5))
print(math.pi)
Output:
8.0
120
3.141592653589793
The random Module

The random module provides functions for generating pseudo-random values.

import random

number = random.randint(1, 10)

print(number)

The output will be an integer between 1 and 10.

The datetime Module

The datetime module is used for working with dates and times.

import datetime

today = datetime.date.today()

print(today)
Example Output:
2026-09-20

The exact output depends on the date when the program runs.

The os Module

The os module provides functions for interacting with the operating system.

import os

print(os.getcwd())

This displays the current working directory.

Module Variables

A module can contain variables in addition to functions.

For example, student.py:

name = "Rahul"
age = 20

Another program can use these variables:

import student

print(student.name)
print(student.age)
Output:
Rahul
20
Module with a Class

A module can also contain classes.

class Student:

    def __init__(self, name):
        self.name = name

    def show(self):
        print(self.name)

If this code is saved in student.py, it can be imported into another Python program.

from student import Student

s = Student("Amit")
s.show()
Output:
Amit
__name__ and __main__

Python provides the special variable __name__. When a Python file is run directly, its value is usually "__main__".

def welcome():
    print("Welcome to Python")

if __name__ == "__main__":
    welcome()

This pattern allows code to run when the file is executed directly, while preventing that block from running just because the module is imported.

Module Search

When Python imports a module, it searches for that module in locations available through Python's module search path.

The search path can be inspected using sys.path.

import sys

print(sys.path)

It displays a list of directories that Python searches when importing modules.

Using Your Own Module

Suppose we have two files in the same folder.

File 1: calculator.py

def add(a, b):
    return a + b

File 2: main.py

import calculator

result = calculator.add(100, 50)

print(result)
Output:
150
Module Naming

A module file normally has the .py extension. It is useful to choose a meaningful module name.

Examples:

calculator.py
student.py
database.py
employees.py
utilities.py
Tip: Use clear and descriptive module names so that other developers can understand the purpose of the module easily.
Module vs Function
Function Module
A reusable block of code. A Python file containing reusable code.
Created using def. Usually stored in a .py file.
Performs a specific task. Can contain functions, classes, variables and other code.
Module vs Package

A module is generally a single Python file, while a package is a way of organizing related Python modules into a directory structure.

Module: calculator.py

Package: A directory containing related modules.

Packages are covered in the next lesson.

Key Points
  • A module is a Python file containing reusable code.
  • Modules can contain functions, variables, classes and statements.
  • The import keyword is used to import modules.
  • from ... import can be used to import specific names.
  • The as keyword can create an alias.
  • Python provides many standard-library modules.
  • You can create your own modules.
  • Modules help organize and reuse code.
  • Packages are used to organize related modules.

🧠 Quick Quiz

Question: Which keyword is used to import a Python module?