What Are Modules?
- A module is a separate file where we write some Python code, like functions, variables, or classes.
- We don’t need to write everything inside one long program. Just split our code into different files (modules).
The module works like a toolbox, which means we keep different tools in one box. Similar to a Python module keeps related code in one file.
Why Use Python Modules?
- Code Reusability: Just write code only one time and use it in multiple programs easily.
- Better Organization: Real-world projects are so big, In this case module become more manageable when split into files.
- Ease of Maintenance: Update code in only one place, without updating each part manually.
- Collaboration: When we work on a real project, team members can work on different modules without disturbing each other.
How To Create a Python Module
A module is created with a .py extension. For example, if you create a file named my_module.py, it becomes a module.
Step 1: Create a Module (save as math_tools.py)
# math_tools.py
# A completely unique and simple module for learning
pi_value = 3.141 # custom lightweight PI value
def circle_area(radius):
return pi_value * radius * radius
def find_biggest(a, b, c):
# unique logic: compare using a simple list trick
numbers = [a, b, c]
biggest = numbers[0]
for num in numbers:
if num > biggest:
biggest = num
return biggest
class SimpleCounter:
def __init__(self):
self.value = 0
def increase(self, step=1):
self.value += step
return self.value
Step 2: Use the Module in Another File (save as main.py)
# main.py
# Importing our custom module
import math_tools
print("Area of circle (radius 5):", math_tools.circle_area(5))
print("Biggest number among 4, 9, 3:", math_tools.find_biggest(4, 9, 3))
counter = math_tools.SimpleCounter()
print("Counter after 1st increase:", counter.increase())
print("Counter after increasing by 3:", counter.increase(3))
Explanation of these examples:
1) math_tools.py is our module, and it contains:
- a variable: pi_value
- two functions: circle_area(), find_biggest()
- one class: SimpleCounter
2) main.py: This is our main program. It imports the module and uses everything inside it.
When you write:
import math_tools
- Python reads that file and gives you access to all the tools stored inside.
Types of Module Imports In Python
We can import program code from modules, but how can we do this? Let’s break down each type of import:
1) Standard Import:
In this type, we import the whole module as it is. After importing, we must use the module name every time we access something inside it.
Example code:
1) my_tools.py
# A fresh and unique example module
def square(n):
return n * n
def welcome(name):
return f"Hello, {name}! Glad you're here."
2) main.py
import my_tools
print(my_tools.square(6))
print(my_tools.welcome("Aarav"))
2) Import Specific Functions or Variables:
In this scenario, we don’t need the whole module. We will import only those items that are actually needed. For example:
1) math_pack.py
def triple(x):
return x * 3
def is_even(num):
return num % 2 == 0
2) main.py
from math_pack import triple, is_even
print(triple(5)) # Only triple imported
print(is_even(12)) # Only is_even imported
3) Import with an Alias
Sometimes module names are long, so Python allows us to assign a nickname (alias).
1) data_helper.py
def words_count(text):
return len(text.split())
def reverse_text(t):
return t[::-1]
2) main.py
import data_helper as dh
print(dh.words_count("Python modules are easy"))
print(dh.reverse_text("importing"))
4) Import All Functions
This method imports everything from a module. You can use all functions directly without writing the module name.
Use this functionality carefully, because it can create confusion with overlapping function names.
Let’s see the example:
1) string_tools.py
def shout(msg):
return msg.upper() + "!!!"
def first_letter(word):
return word[0] if word else ""
2) main.py
from string_tools import *
print(shout("python modules"))
print(first_letter("Coding"))
Learn Built-in Python Modules
Python already includes many ready-made modules that provide powerful features, so we don’t need to write everything manually.
These modules are automatically installed with Python, so we can use them anytime without downloading anything.
There are some ready-made modules available like:
- math → for mathematical formulas
- random → for random numbers
- os → for working with files and folders
- datetime → for dates and time
- statistics → for basic data analysis
Example: Using the math Module
“Find the Hypotenuse of a Triangle + Compare Two Angles”
import math
# Lengths of two sides of a right-angled triangle
side_a = 5
side_b = 12
# Using math module to calculate hypotenuse
hypotenuse = math.sqrt(side_a**2 + side_b**2)
# Using math.radians and math.sin to compare angles
angle_small = 30
angle_big = 60
sin_small = math.sin(math.radians(angle_small))
sin_big = math.sin(math.radians(angle_big))
print("Hypotenuse:", hypotenuse)
print("Sin(30°):", sin_small)
print("Sin(60°):", sin_big)
Output:
Hypotenuse: 13.0
Sin(30°): 0.49999999999999994
Sin(60°): 0.8660254037844386
How To Create Custom Modules In Python?
We are not limited to using only built-in modules like math or random. Now we will create our own modules that can store reusable code.
Example: Custom Module with Constants
Step 1: Create a module file with named math_constants.py
# A custom module that stores special mathematical values
# (Unique values chosen for learning purpose)
CIRCLE_RATIO = 0.31831 # Just a sample constant for demonstration
MAX_SPEED_LIMIT = 120 # Could represent km/h in a simulation
def describe_constants():
return "These constants are used for demo calculations in geometry and motion."
Step 2: Use the Custom Module
- Create another file where you import and use it.
main.py
import math_constants
print("Circle Ratio:", math_constants.CIRCLE_RATIO)
print("Top Speed Limit:", math_constants.MAX_SPEED_LIMIT)
print("Info:", math_constants.describe_constants())
Output will be this:
Circle Ratio: 0.31831
Top Speed Limit: 120
Info: These constants are used for demo calculations in geometry and motion.
Organizing Modules with Packages
Sometimes, a Python file becomes so hard when we handle our whole project in a single Python file.
For this reason, we are using a package, because it is a simple folder that contains multiple Python modules.
Imagine a package is a school bag where:
- The bag → package
- The books → modules
- The index page inside the bag (__init__.py) → tells Python “This bag contains usable files.”
Example With Package Structure
Let’s create a package named smart_math that contains two modules:
- adder.py → adds numbers
- multiplier.py → multiplies numbers
📁 Folder Structure
smart_math/
__init__.py
adder.py
multiplier.py
Code Example:
- adder.py
def add_safely(a, b):
# Adds numbers but also checks if both are positive
if a < 0 or b < 0:
return "Only positive numbers allowed!"
return a + b
- multiplier.py
def double_and_multiply(a, b):
# Doubles each number first, then multiplies
doubled_a = a * 2
doubled_b = b * 2
return doubled_a * doubled_b
- __init__.py
# This file makes the folder a valid Python package
Using the Package in Your Main Python File
from smart_math.adder import add_safely
from smart_math.multiplier import double_and_multiply
result1 = add_safely(4, 6)
result2 = double_and_multiply(3, 5)
print("Safe Addition:", result1)
print("Double Multiply:", result2)
Output:
Safe Addition: 10
Double Multiply: 60
Important Module Functions
Python gives us some built-in functions that allow us to inspect modules, check their contents, and understand how to use them.
Below are two functions we can use in our projects:
1) dir(module): dir() is like a microscope that shows all the things stored inside a module, such as functions, constants, classes, variables, and even internal helper tools.
- In this code, we will find only those names that start with the letter “c”.
import math
# Show only the names from math module that start with 'c'
items_starting_with_c = [item for item in dir(math) if item.startswith("c")]
print("Math module items starting with 'c':")
print(items_starting_with_c)
2) help(module): help() opens a detailed explanation about the module. It shows:
- What the module does
- Description of its functions
- Parameters
- Examples
For example:
import random
# Print a short help guide for the random module
print("=== Random Module Quick Documentation ===")
help(random.choice) # Getting help for specific function
Common Errors and How to Avoid Them
1) Module Not Found Error: This error appears when Python tries to import a module, but it has no idea where that module is located.
This error happens when:
- The module file doesn’t exist.
- You misspelled the module name.
- The file is not in the same folder or Python’s search path.
import magic_box # This module does not exist, so Python raises an error
2) Circular Import Error: This happens when module A imports module B, and at the same time module B imports module A.
- What Are Modules In Python?
- What Is a Function In Python?
- What Is Python String Formatting?
- What Is a Python List?
- How Can We Use Lambda Function?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.