How do you import a Python module and use its functions?

0127

To import a Python module and use its functions, follow these steps:

  1. Import the Module: Use the import statement to bring the module into your current program.

    import module_name
  2. 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.

0 Comments

no data
Be the first to share your comment!