To import a Python module and use its functions, follow these steps:
-
Import the Module: Use the
importstatement to bring the module into your current program.import module_name -
Access Functions: Use dot notation to access functions or variables defined in the module.
module_name.function_name()
Example
Suppose you have a module named math_utils.py with a function add:
# math_utils.py
def add(a, b):
return a + b
You can import and use it as follows:
# main.py
import math_utils
result = math_utils.add(5, 3)
print(result) # Output: 8
Alternative Import Method
You can also import specific functions directly:
from math_utils import add
result = add(5, 3)
print(result) # Output: 8
This way, you can call add() directly without the module prefix.
