Introduction
Python modules help organize code into reusable files, making large applications easier to manage. A module is simply a Python file containing functions, classes, or variables you can use in other Python programs.
Objective
In this guide, you will learn how to:
- Create a custom Python module
- Import and use that module in another script
- Understand the structure and how to execute it
Step 1: Create a Python Module
Save the following code in a file named mymodule.py
:
# mymodule.py
def greet(name):
return f"Hello, {name}! Welcome to Python modules."
def add(a, b):
return a + b
Step 2: Use the Module in Another File
Now create another file named main.py
in the same directory:
# main.py
import mymodule
# Using functions from mymodule
message = mymodule.greet("Alice")
sum_result = mymodule.add(10, 5)
print(message)
print("Sum:", sum_result)
Explanation
mymodule.py
defines two functions: greet()
and add()
. These functions are available to any file that imports this module using import mymodule
.
In main.py
, we import the module and use its functions by referencing them as mymodule.function_name()
.
How to Run the Program
- Make sure both
mymodule.py
andmain.py
are in the same folder. - Open a terminal or command prompt and navigate to that folder.
- Run the following command:
python main.py
You should see this output:
Hello, Alice! Welcome to Python modules.
Sum: 15