To import a module in Python, you can use the import statement. Here are a few common ways to import modules:
Importing the Entire Module: You can import the entire module using the
importstatement. For example, to import a module namedmymodule, you would write:import mymoduleAfter importing, you can access functions or classes from the module using the dot notation:
mymodule.my_function()Importing Specific Functions or Classes: If you only need specific functions or classes from a module, you can use the
from ... importsyntax. For example:from mymodule import my_functionNow you can call
my_function()directly without the module prefix:my_function()Importing with an Alias: You can also import a module and give it a shorter alias using the
askeyword. This is useful for long module names:import mymodule as mmYou can then use the alias to access the module:
mm.my_function()Importing All Functions from a Module: If you want to import all functions and classes from a module, you can use the asterisk
*:from mymodule import *However, this is generally not recommended as it can lead to confusion with naming conflicts.
Example
Here's a complete example using a hypothetical module named math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
You can import and use it like this:
# main.py
import math_utils
result = math_utils.add(5, 3)
print(result) # Output: 8
Feel free to ask if you have any more questions!
