CREATING AND USING CUSTOM MODULES

Creating and using custom modules in Python is a great way to organize and reuse code across multiple programs. Here's a step-by-step guide on how to create and use your own custom modules:

1. Create the Custom Module: To create a custom module, follow these steps:

a. Open a new text editor or Python IDE. b. Write the functions, classes, or variables you want to include in your module. c. Save the file with a .py extension, using a descriptive name for your module.

For example, let's create a simple custom module named mymath that contains some basic mathematical functions:

mymath.py

python
def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): return a / b

2. Using the Custom Module: To use the custom module in your main program, follow these steps:

a. Ensure that the custom module file (mymath.py in this case) is in the same directory as your main program file or provide the correct path to the module file.

b. Import the custom module using the import statement in your main program.

main.py

python
import mymath result_add = mymath.add(5, 3) print("Addition:", result_add) # Output: Addition: 8 result_subtract = mymath.subtract(10, 5) print("Subtraction:", result_subtract) # Output: Subtraction: 5 result_multiply = mymath.multiply(2, 4) print("Multiplication:", result_multiply) # Output: Multiplication: 8 result_divide = mymath.divide(10, 2) print("Division:", result_divide) # Output: Division: 5.0

In the main.py file, we import the custom module mymath and use the functions add, subtract, multiply, and divide defined in the mymath.py module.

3. Executing the Program: To execute the main program, run the main.py file, and it will import the custom module and utilize its functions as defined.

Keep in mind the following tips:

  • Make sure the custom module file has the .py extension and is in the same directory as the main program file or in a directory accessible by the Python interpreter.

  • When importing the custom module, the name of the module (e.g., mymath) should match the filename without the .py extension.

With this approach, you can easily create and use custom modules to organize and share your Python code more effectively. Custom modules help maintain clean and modular code and make it easier to manage larger projects.