A technical infographic titled 'Custom Modules in Python' showing: Module Structure: Python file (.py) with functions (e.g., calculate_tax()), classes, and docstrings Import Process: import my_module → my_module.function() syntax examples Use Case: A finance module with currency converter and loan calculator functions Best Practices: Naming conventions, __init__.py for packages, and error handling.

Custom modules

Creating and Using Custom Python Modules

Module 1: calculations.py

# calculations.py
def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
def multiply(x, y):
    return x * y
def divide(x, y):
    if y != 0:
        return x / y
    else:
        return "Error: Division by zero is not allowed."

Module 2: greetings.py

# greetings.py
def greet(name):
    return f"Hello, {name}!"

Module 3: squares.py

# squares.py
def square(n):
    return n ** 2

Main Program: main.py

import calculations
import greetings
import squares
print(calculations.add(10, 5))      # Output: 15
print(calculations.subtract(10, 5)) # Output: 5
print(calculations.multiply(10, 5)) # Output: 50
print(calculations.divide(10, 5))   # Output: 2.0
print(greetings.greet("Alice"))     # Output: Hello, Alice!
print(squares.square(5))            # Output: 25

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top