Using modules, we can modularize the larger codebase into smaller parts which promotes code reusability, and maintainability. While Python provides a rich set of built-in modules, we often need to create our own custom modules to hide some specific functionalities. In this article, we will see how to create a module and import our own modules in Python.

Let’s first create the sample Python module with the following content and name it and save it in the same directory where the main Python script is present.

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

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

In the main Python script, import the above module using the import as shown below.

import my_module

result = my_module.add(3, 5)

In the above example, we import the my_module and by prefixing the module name we can use the greet() and add() functions.

Import specific functions

We can also import the specific functions from my_module instead of importing all the functions by using the from keyword.

from my_module import greet, add

result = add(2, 4)

    Categorized in:

    Tagged in: