Python as Keyword
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:
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”.
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.
No module named 'maths' No file found
My Personal Notes arrow_drop_up
Please Login to comment...