The Python as keyword is used to create an alias, which means shorten name of particular module or file or error. It is a case-sensitive keyword.
The as keyword is used in importing modules, file exception handling and in files. It makes the code more understandable. This keyword is used to make selected name by the programmer in a code, It decreases the chance coincide of the name of the module with the variable name.
Using 'as' Keyword in ModulesThe as keyword is used in importing a module. This keyword works with import statement and It is always after the resource to which it is an alias.
ExampleHere, we have imported array module and alias it has arr using as keyword −
import array as arr myArray = arr.array('i',[1,2,3,4,5]) print(myArray)
Output
Following is the output of the above code −
array('i', [1, 2, 3, 4, 5])Using 'as' Keyword in Files
Keyword as is used by the with an open statement to make an alias for its a resource. Here in as.txt file have text "Tutorialspoint".
ExampleHere, is an usage of as keyword in files −
def Tutorialspoint(): with open('sample.txt') as Tp: data = Tp.read() # Printing our text print(data) Tutorialspoint()
Output
Following is the output of the above code −
Hello welcome to TutorialspointUsing 'as' Keyword in Exception Handling
In Exception handling we can use the as keyword to short the exception.
ExampleHere, we have used as keyword in exception handling −
var1 = 5 var2 = 0 try: print(var1/var2) except Exception as e: print("Error:",e)
Output
Following is the output of the above code −
Error: division by zero
python_keywords.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4