Of course! A Python module is simply a Python file (.py) that contains Python code. This code can be functions, classes, or variables. You can then import and use this code in other Python files.

Let's break down what a module is, how to create one, and how to use it.
What is a Module?
A module is a single file that organizes related code. Think of it like a toolbox. Instead of having all your tools (functions and classes) scattered around the workshop, you put them in a toolbox (a module) so you can carry them around and use them when needed.
Key Benefits:
- Organization: Keeps your code clean and manageable.
- Reusability: Write a module once and use it in many different projects.
- Namespace: Prevents naming conflicts. For example, you can have a function named
calculate_areain yourgeometry.pymodule and another in yourfinance.pymodule without them clashing.
How to Create a Module
Creating a module is as simple as creating a Python file.

Let's create a module named math_utils.py that will contain some useful mathematical functions.
File: math_utils.py
# This is our custom module file.
# A constant variable defined at the module level
PI = 3.14159
# A simple function
def add(a, b):
"""Adds two numbers and returns the result."""
return a + b
# A more complex function
def calculate_circle_area(radius):
"""Calculates the area of a circle given its radius."""
if radius < 0:
raise ValueError("Radius cannot be negative.")
return PI * (radius ** 2)
# A class
class Rectangle:
"""A class to represent a rectangle."""
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
# This block will only run when the script is executed directly,
# not when it's imported as a module.
if __name__ == "__main__":
print("Running math_utils.py directly...")
print(f"PI is: {PI}")
print(f"5 + 3 = {add(5, 3)}")
print(f"Area of a circle with radius 10: {calculate_circle_area(10)}")
my_rect = Rectangle(4, 5)
print(f"Area of a 4x5 rectangle: {my_rect.area()}")
How to Use a Module
Now, let's create another Python script (e.g., main.py) in the same directory and use the code from our math_utils.py module.
File: main.py

# Import the entire module
import math_utils
# Now you can access everything from math_utils using the module name as a prefix.
print(f"Value of PI from the module: {math_utils.PI}")
print(f"10 + 20 = {math_utils.add(10, 20)}")
# Use the class from the module
rect1 = math_utils.Rectangle(10, 2)
print(f"Perimeter of a 10x2 rectangle: {rect1.perimeter()}")
# --- Other ways to import ---
# 1. Import specific items (you don't need the module prefix)
from math_utils import calculate_circle_area, Rectangle
print("\n--- Using specific imports ---")
print(f"Area of a circle with radius 7: {calculate_circle_area(7)}")
rect2 = Rectangle(3, 3)
print(f"Area of a 3x3 square: {rect2.area()}")
# 2. Import with an alias (useful for long module names or to avoid conflicts)
import math_utils as mu
print("\n--- Using an alias ---")
print(f"Area of a circle with radius 15: {mu.calculate_circle_area(15)}")
When you run main.py from your terminal (python main.py), the output will be:
Value of PI from the module: 3.14159
10 + 20 = 30
Perimeter of a 10x2 rectangle: 24
--- Using specific imports ---
Area of a circle with radius 7: 153.93791
Area of a 3x3 square: 9
--- Using an alias ---
Area of a circle with radius 15: 706.85835
Notice that the if __name__ == "__main__": block in math_utils.py did not run. That's because that code only executes when the file is run directly, not when it's imported.
Common Built-in Modules
Python comes with a huge library of standard modules. Here are a few you'll use often:
| Module Name | Description | Example |
|---|---|---|
math |
Mathematical functions and constants. | import mathprint(math.sqrt(16))print(math.factorial(5)) |
random |
Generating random numbers. | import randomprint(random.randint(1, 10))print(random.choice(['apple', 'banana', 'cherry'])) |
datetime |
Working with dates and times. | from datetime import datetimenow = datetime.now()print(f"Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}") |
os |
Interacting with the operating system. | import osprint(os.listdir('.')) # List files in current directoryos.makedirs('new_folder') |
json |
Parsing JSON data. | import jsondata = '{"name": "Alice", "age": 30}'parsed_data = json.loads(data)print(parsed_data['name']) |
sys |
Accessing system-specific parameters. | import sysprint(sys.argv) # List of command-line argumentsprint(sys.path) # List of directories to search for modules |
The __pycache__ Directory
You might notice a __pycache__ folder appear after you run a script that imports modules. This is normal!
- What it is: Python automatically compiles your
.pyfiles into bytecode (.pycfiles) to speed up future imports. - Why it exists: The next time you import that module, Python can load the pre-compiled bytecode instead of re-parsing the text file, which is much faster.
- Can you ignore it? Yes. You can safely add
__pycache__/to your.gitignorefile. You can also delete it at any time; Python will just recreate it the next time you run your code.
