PYTHON Tutorial
Modules and packages are organizational units in Python code. Modules are individual Python files containing code that can be imported into other Python programs, while packages are collections of related modules.
Create a new Python file (.py) and define functions, classes, or variables in it. Save it as your_module.py
.
In another Python program, use the import
statement to import the module:
import your_module
You can then access the module's contents using the module name, e.g.:
your_module.function()
Create a new directory and place your related modules within it. Create an __init__.py
file in the directory to indicate that it is a package.
Use the import
statement to import the package:
import your_package
You can then access modules within the package using the package name, e.g.:
your_package.your_module.function()
Creating the Module math_utils.py
:
def add_numbers(a, b):
return a + b
Using the Module in Another Program:
import math_utils
result = math_utils.add_numbers(3, 5)
print(result) # Output: 8
This example demonstrates how to create and use a module to perform simple mathematical operations.