Basic Import

The import statement in Python is used to include the definitions (functions, classes, variables) from a module into the current namespace. This allows you to use functions and classes defined in other files or modules.

# Import the entire math module
import math

# Use a function from the math module
result = math.sqrt(16)
print(result)  # Output: 4.0

Import With Alias

The import statement in Python allows you to import a module with an alias. This is useful when you want to refer to a module with a different name in your code.

# Import the math module with an alias
import math as m

# Use a function from the math module using the alias
result = m.sqrt(16)
print(result)  # Output: 4.0

Import Specific Functions or Classes

In Python, you can import specific functions or classes from a module instead of importing the entire module.

# Import specific functions from the math module
from math import sqrt, pi

# Use the imported functions directly
result = sqrt(16)
print(result)  # Output: 4.0

# Access the imported constant
print(pi)  # Output: 3.141592653589793

Import All Definitions From a Module

In Python, you can import all definitions (functions, classes, variables) from a module using the * operator. This allows you to use all the definitions from the module without having to prefix them with the module name.

# Import all functions and variables from the math module
from math import *

# Use the imported functions directly
result = sqrt(16)
print(result)  # Output: 4.0

# Access the imported constant
print(pi)  # Output: 3.141592653589793