Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Modules Import BasicsCreating ModulesImport StatementsRelative ImportsImport PathsPackages StructureNamespace PackagesPip & DependenciesModule Performance
Python/Modules Packages/Creating Modules

🛠️ Creating Modules — Write Reusable Code

Creating your own modules is simple: just write Python code in a `.py` file! Then you can import and use that code in other programs.


🎯 Your First Module

A module is any `.py` file with functions, classes, or variables.

# calculator.py (our first module)
def add(a, b):
    """Add two numbers and return the result."""
    return a + b

def multiply(a, b):
    """Multiply two numbers and return the result."""
    return a * b

def divide(a, b):
    """Divide a by b, return None if b is zero."""
    if b == 0:
        return None
    return a / b

# Module-level variable
OPERATIONS = ["add", "multiply", "divide"]
# main.py (using our module)
import calculator

print(calculator.add(10, 5))       # 15
print(calculator.multiply(4, 3))   # 12
print(calculator.divide(20, 4))    # 5.0
print(calculator.OPERATIONS)       # ['add', 'multiply', 'divide']

💡 Module File Structure

Modules should be well-organized with docstrings and comments.

# weather.py - A realistic module example

"""
weather module - Provides functions for weather-related calculations.

This module includes utilities for temperature conversion,
wind chill calculation, and heat index computation.
"""

# Constants at the top
CELSIUS_TO_FAHRENHEIT_OFFSET = 32
CELSIUS_TO_FAHRENHEIT_RATIO = 9 / 5

# Functions grouped logically
def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit."""
    return celsius * CELSIUS_TO_FAHRENHEIT_RATIO + CELSIUS_TO_FAHRENHEIT_OFFSET

def fahrenheit_to_celsius(fahrenheit):
    """Convert Fahrenheit to Celsius."""
    return (fahrenheit - CELSIUS_TO_FAHRENHEIT_OFFSET) / CELSIUS_TO_FAHRENHEIT_RATIO

def is_freezing(celsius):
    """Check if temperature is freezing (0°C or below)."""
    return celsius <= 0

def heat_index(temp_f, humidity):
    """Calculate heat index (apparent temperature)."""
    if humidity < 40 or temp_f < 80:
        return temp_f
    # Simplified heat index formula
    return temp_f + (humidity - 40) * 0.1

🎨 Modules with Classes

Modules can contain classes for more complex functionality.

# person.py - Module with a class

class Person:
    """A class representing a person."""

    def __init__(self, name, age):
        """Initialize a person with name and age."""
        self.name = name
        self.age = age

    def greet(self):
        """Return a greeting message."""
        return f"Hello, I'm {self.name} and I'm {self.age} years old."

    def birthday(self):
        """Increment age by one."""
        self.age += 1
        return f"Happy birthday! Now {self.age} years old."

class Student(Person):
    """A class representing a student."""

    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def get_info(self):
        """Return student information."""
        return f"{self.name} (ID: {self.student_id})"
# Using the person module
from person import Person, Student

alice = Person("Alice", 25)
print(alice.greet())  # Hello, I'm Alice and I'm 25 years old.

bob = Student("Bob", 20, "S12345")
print(bob.get_info())  # Bob (ID: S12345)

🏗️ Module with Helper Functions

Organize related functions together.

# string_utils.py - Utilities for string manipulation

def reverse_string(text):
    """Return the reversed string."""
    return text[::-1]

def count_vowels(text):
    """Count the number of vowels in the string."""
    vowels = "aeiouAEIOU"
    return sum(1 for char in text if char in vowels)

def title_case_words(text):
    """Convert to title case (first letter of each word capitalized)."""
    return " ".join(word.capitalize() for word in text.split())

def is_palindrome(text):
    """Check if string is a palindrome (ignoring spaces)."""
    clean = text.replace(" ", "").lower()
    return clean == clean[::-1]

def count_words(text):
    """Count the number of words in the string."""
    return len(text.split())
# Using string utilities
import string_utils

text = "hello world"
print(string_utils.reverse_string(text))      # dlrow olleh
print(string_utils.count_vowels(text))        # 3
print(string_utils.title_case_words(text))    # Hello World
print(string_utils.count_words(text))         # 2

if string_utils.is_palindrome("race car"):
    print("It's a palindrome!")  # Prints this

📦 Module Naming Best Practices

# ✅ Good module names (use lowercase, underscores for multiple words)
# math_helpers.py
# user_authentication.py
# data_processing.py
# api_client.py

# ❌ Avoid these (confusing names, conflicts with built-ins)
# Math.py (conflicts with built-in 'math' module)
# my.py (unclear what it does)
# utils.py (too generic)
# a.py (no information)

🔄 Testing Your Module

It's good practice to test modules before using them elsewhere.

# calculator.py with testing

def add(a, b):
    """Add two numbers."""
    return a + b

def divide(a, b):
    """Divide a by b."""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

# Test the module when run directly
if __name__ == "__main__":
    # These tests only run if calculator.py is run directly,
    # not when it's imported
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert divide(10, 2) == 5

    try:
        divide(10, 0)
    except ValueError:
        print("Error handling works!")

    print("All tests passed!")

📊 Module Organization Example

# data_validation.py - A well-structured module

"""
data_validation - Utilities for validating user input.

Functions:
    - is_valid_email(email): Check if email format is valid
    - is_valid_phone(phone): Check if phone number is valid
    - is_valid_password(password): Check password strength
"""

import re

def is_valid_email(email):
    """Check if email has basic valid format."""
    pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    return re.match(pattern, email) is not None

def is_valid_phone(phone):
    """Check if phone number has valid format (10 digits)."""
    digits = re.sub(r"\D", "", phone)
    return len(digits) == 10

def is_valid_password(password):
    """Check if password meets minimum requirements."""
    if len(password) < 8:
        return False
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    return has_upper and has_lower and has_digit

def validate_user_data(name, email, phone, password):
    """Validate all user data and return results."""
    errors = []

    if not name or len(name) < 2:
        errors.append("Name must be at least 2 characters")

    if not is_valid_email(email):
        errors.append("Email format is invalid")

    if not is_valid_phone(phone):
        errors.append("Phone must have 10 digits")

    if not is_valid_password(password):
        errors.append("Password must be 8+ chars with uppercase, lowercase, and digit")

    return len(errors) == 0, errors

🔑 Key Takeaways

  • ✅ A module is simply a `.py` file with Python code
  • ✅ Any Python file can be imported as a module
  • ✅ Include docstrings to document your module's purpose
  • ✅ Organize related functions and classes together
  • ✅ Use lowercase names with underscores for module files
  • ✅ Test modules before importing them in other projects

Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn