Python Module
- A module is a file in Python that contains functions, definitions, and statements that can be imported into another Python script. A technique for organizing code into logical, reusable parts. You can break up your code into smaller, easier-to-manage files with modules, making it simpler to update, test, and debug your code.
- To make a module in Python, you essentially have to characterize your capabilities, classes, and factors in a .py record.
To Create A Module:
Open a new file with a .py extension.
Define functions, classes, and variables in the file.
Save the file with a meaningful name (this will be the name of the
module).
Example:
module file (example_module.py)
Program:
def greet(name):
print(f"Hello, {name}!")
def add_numbers(a, b):
return a + b
greeting = "Welcome to my module!"
result =add_numbers(5, 7)
print(greeting)
greet("Gocourse")
print("sum of a & b:",result)
Output:
Welcome to my module!
Hello, Gocourse!
sum of a & b: 12
To Use A Module:
Import the module into your Python script using the import keyword.
Access the functions, classes, and variables defined in the module using
the module name and dot notation.
Example :
script (example_script.py)
Program:
import example_module
example_module.greet("Students")
result = example_module.add_numbers(3, 4)
print(result)
print(example_module.greeting)
Output:
Hello, Students
7
Welcome to my module!
More topic in Python