The as keyword is used to create an alias for a module, object, exception, or file. It helps make code shorter, more readable, and easier to work with.
import math as m
print(m.sqrt(16))
Output
4.0
Explanation: statement import math as m creates the alias m for the math module. The function m.sqrt(16) uses the alias to calculate the square root of 16.
Syntax
import module_name as alias_name
Parameters:
- module_name: The module to import.
- alias_name: The new name used to refer to the imported module.
Returns: Creates an alias for the imported module, making it accessible through the specified name.
Examples
Example 1: Here, we import the sqrt() function from the math module and give it the alias square_root.
from math import sqrt as square_root
print(square_root(49))
Output
7.0
Explanation: statement from math import sqrt as square_root imports only the sqrt() function and renames it to square_root. The alias is then used to calculate the square root of 49.
Example 2: Here, we open a file and read its contents using the as keyword.
with open("sample.txt", "r") as file:
content = file.read()
print(content)
Output
Hello, Python!
Explanation: variable file refers to the opened file inside the with block. After the block finishes, the file is automatically closed.
Example 3: Here, we catch a ZeroDivisionError and display its error message.
try:
result = 10 / 0
except ZeroDivisionError as error:
print(error)
Output
division by zero
Explanation: statement except ZeroDivisionError as error stores the exception object in error, which is then printed.