0
0
Pythonprogramming~5 mins

Creating custom modules in Python

Choose your learning style9 modes available
Introduction

Custom modules help you organize your code into separate files. This makes your programs easier to read and reuse.

You want to split a big program into smaller parts.
You want to reuse functions or classes in different programs.
You want to share your code with friends or coworkers.
You want to keep your main program file clean and simple.
Syntax
Python
Create a file named mymodule.py:

def greet(name):
    return f"Hello, {name}!"

In another file, import and use it:

import mymodule

print(mymodule.greet("Alice"))

The module file must have a .py extension.

Use import module_name to use the module in another file.

Examples
This example shows a simple function in a module and how to call it.
Python
# mymodule.py

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

# main.py

import mymodule

print(mymodule.add(3, 4))
This example imports only the area function from the module.
Python
# mymodule.py

PI = 3.14

def area(radius):
    return PI * radius * radius

# main.py

from mymodule import area

print(area(5))
This example shows how to import and use a class from a custom module.
Python
# mymodule.py

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

    def greet(self):
        return f"Hi, I am {self.name}."

# main.py

from mymodule import Person

p = Person("Bob")
print(p.greet())
Sample Program

This program creates a module with a multiply function. The main program imports it and prints the result.

Python
# file: mymodule.py

def multiply(x, y):
    return x * y

# file: main.py

import mymodule

result = mymodule.multiply(6, 7)
print(f"6 times 7 is {result}")
OutputSuccess
Important Notes

Make sure the module file is in the same folder as your main program or in Python's search path.

You can import multiple functions or classes using commas: from module import func1, func2.

Use as to rename modules or functions when importing for easier use.

Summary

Custom modules help organize and reuse code.

Create a module by saving functions or classes in a .py file.

Import modules using import or from ... import to use their code.