Creating a Python module is a way to organize your Python code into reusable components. A module is a file containing Python definitions and statements that can be imported and used in other Python scripts.
Here’s how you can create a simple Python module quickly:
Step #1 Preparation steps
- Open your preferred text editor or IDE (such as vscode).
- Create a new Python file with a .py extension.
- Choose a meaningful name for your module.
- For example, let’s call it codetryout.py.
- Write your Python code in the codetryout.py file.
You can define functions, classes, variables, or any other Python code you want to include in your module.
Step #2 Create the module File
File Name codetryout.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
Save the codetryout.py file in a directory where your main Python scripts can access it. It’s a good idea to create a dedicated folder for your modules and place your module files there.
Step #3 Creating file main.py
Now you can use the module in other Python scripts by importing it. To import the codetryout module from the example above, you can create a new Python script (let’s call it main.py) and import the functions from codetryout like this:
File Name: main.py
import codetryout
result_add = codetryout.add(5, 3)
print("Addition:", result_add)
result_subtract = codetryout.subtract(10, 4)
print("Subtraction:", result_subtract)
result_multiply = codetryout.multiply(2, 6)
print("Multiplication:", result_multiply)
Save the main.py script in the same directory as your codetryout.py module.
Step #4 Run your Script with your newly created Python module!
Run the main.py script, and it will use the functions from your module to perform the calculations and print the results.
Addition: 8
Subtraction: 6
Multiplication: 12
You have created a Python module and used it in another Python script. You can add more functions, classes, or variables to your module and reuse them in multiple Python scripts by importing the module. Modules are a powerful way to organize your code and promote code reusability.