Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python as Keyword



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 Modules

The 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.

Example

Here, 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".

Example

Here, 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 Tutorialspoint

Using 'as' Keyword in Exception Handling

In Exception handling we can use the as keyword to short the exception.

Example

Here, 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
Advertisements