USER DEFINED MODULES
User-defined modules in Python are Python files that contain reusable code, including functions, classes, and variables, which can be imported and used in other Python scripts or modules. Creating user-defined modules allows you to organize your code into logical units and promote code reuse across different projects.
Here’s how you can create and use a user-defined module:
1. Create a Python File: Start by creating a Python file with a `.py` extension. This file will contain the code for your module.
2. Write Your Code: Inside the Python file, define the functions, classes, or variables that you want to include in your module. For example, you might define a set of utility functions or a custom class.
3. Save the File: Save the Python file in the directory where you want to store your modules or in a location accessible to your Python interpreter.
4. Import Your Module: In other Python scripts or modules where you want to use your user-defined module, import it using the `import` statement followed by the name of your module (without the `.py` extension).
Here’s a simple example of creating and using a user-defined module:
1. Create a Module File (e.g., `my_module.py`):
“`python
# my_module.py
def greet(name):
return f”Hello, {name}!”
def square(x):
return x 2
PI = 3.14159
“`
2. Use the Module in Another Script:
“`python
# main.py
import my_module
print(my_module.greet(“Alice”)) # Output: Hello, Alice!
print(my_module.square(5)) # Output: 25
print(my_module.PI) # Output: 3.14159
“`
In this example, `my_module.py` is the user-defined module containing the `greet()` function, the `square()` function, and the variable `PI`. In `main.py`, we import `my_module` and use its functions and variables as needed.
By organizing your code into modules, you can improve code readability, maintainability, and reusability across your Python projects.