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
import random as geek
def Geek_Func():
geek_RandomNumber = geek.randint( 5 , 10 )
geek_RandomNumber2 = geek.randint( 1 , 5 )
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
def geek_Func():
with open ( 'sample.txt' ) as geek:
geek_read = geek.read()
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
try :
import maths as mt
except ImportError as err:
print (err)
def geek_Func():
try :
with open ( 'geek.txt' ) as geek:
geek_read = geek.read()
print ( "Reading alias:" )
print (geek_read)
except FileNotFoundError as err2:
print ( 'No file found' )
geek_Func()
|
Output:
No module named 'maths'
No file found
Last Updated :
12 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...