In this article, we are going to see ‘as’ Keyword. The keyword ‘as’ is used to create an alias in python.
Advantages with ‘as’ keyword:
- It is useful where we cannot use the assignment operator such as in the import module.
- It makes code more understandable to humans.
- The keyword as is used to make alias with programmer selected name, It decreases the chance coincide of the name of the module with the variable name.
Demonstrating working concepts of ‘as’ keyword:
Example 1: Create Alias for the module
Keyword ‘as’ is always after the resource to which it is an alias. ‘as’ keyword works with import statement to assign an alias to it’s a resource:
Python3
# Python code to demonstrate # 'as' keyword # Import random module with alias import random as geek # Function showing working of as keyword def Geek_Func(): # Using random module with alias geek_RandomNumber = geek.randint( 5 , 10 ) geek_RandomNumber2 = geek.randint( 1 , 5 ) # Printing our number print (geek_RandomNumber) print (geek_RandomNumber2) Geek_Func() |
Output:
9 1
Example 2: as with a file
Keyword ‘as’ is used by the with an open statement to make an alias for its a resource. Here in sample.txt file have text “Hello Geeks For Geeks”.
Python3
# Python code to demonstrate # 'as' keyword def geek_Func(): # With statement with geek alias with open ( 'sample.txt' ) as geek: # reading text with alias geek_read = geek.read() # Printing our text print ( "Text read with alias:" ) print (geek_read) geek_Func() |
Output:
Text read with alias: Hello Geeks For Geeks
Example 3: as in Except clause
Here, we are going to use as in except clause along with try.
Python3
# Python code to demonstrate # 'as' keyword # Using alias with try statement try : import maths as mt except ImportError as err: print (err) # Function showing alias functioning def geek_Func(): try : # With statement with geek alias with open ( 'geek.txt' ) as geek: # reading text with alias geek_read = geek.read() # Printing our text print ( "Reading alias:" ) print (geek_read) except FileNotFoundError as err2: print ( 'No file found' ) geek_Func() |
Output:
No module named 'maths' No file found