Importing Built-in Modules
🔹 Use the import
statement to include built-in Python modules.
import math
print(math.sqrt(16)) # Output: 4.0
🔸 You can import specific functions or variables using from ... import ...
.
from math import pi, pow
print(pi) # Output: 3.141592653589793
print(pow(2, 3)) # Output: 8.0
Using Aliases
🔹 Use as
to rename modules or functions when importing.
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
User-defined Modules
🔹 Create your own Python file (module) and import it.
For example, create mymodule.py
:
# mymodule.py
def greet(name):
print("Hello, " + name)
Then import and use it in another file:
import mymodule
mymodule.greet("Alice")
Module Search Path
🔹 Python searches for modules in the directories listed in sys.path
.
import sys
print(sys.path)
🔸 Make sure your user-defined module is in one of these directories or the current working directory.
Summary
- Use
import
to load modules. - Use
from ... import ...
to import specific components. - Use
as
to alias modules or functions. - User-defined modules can be imported as long as they are in the search path.