as keyword in Python plays a important role in simplifying code, making it more readable and avoiding potential naming conflicts. It is mainly used to create aliases for modules, exceptions and file operations. This powerful feature reduces verbosity, helps in naming clarity and can be essential when multiple modules have similar names or when managing file operations.
Example:
Python # Using `as` to alias an imported module import math as m # Using a function from the math module with the alias print(m.sqrt(16))
Examples of using the as keyword
Example 1: Create Alias for the module
The most common use of the as keyword is to assign a short alias to a module when importing it. This makes the code cleaner, especially when working with long module names. It also helps in preventing conflicts with existing variables in our code.
Python # Import random module with alias import random as geek # Using random module with alias to generate random numbers a = geek.randint(5, 10) b = geek.randint(1, 5) # Printing the generated random numbers print(a,b)
Explanation: In this example, the random module is imported with the alias geek. This simplifies the code and we use geek instead of random to generate random numbers.
Example 2: as with a file
as keyword in file operations allows using the open() function within a with statement, ensuring files are automatically closed after the operation.
Python # Using 'as' keyword with 'open' function with open('sample.txt') as geek: # Reading text with alias geek_read = geek.read() # Printing the text read from the file print("Text read with alias:") print(geek_read)
Output:
Text read with alias:
Hello Geeks For Geeks
Explanation: This code opens a file called sample.txt using the open function and assigns it to the alias geek. Then, it reads and prints the contents of the file.
Example 3: as in Except clause
as keyword in the except clause allows assigning the caught exception to a variable for more specific handling or inspection.
Python # Demonstrating 'as' keyword with exception handling try: import maths as mt except ImportError as err: print(err) try: # With statement with 'geek' alias with open('geek.txt') as geek: # Reading text with alias geek_read = geek.read() # Printing the read text print("Reading alias:") print(geek_read) except FileNotFoundError as err2: print('No file found')
Output:
No module named 'maths'
No file found
Explanation: In this case, the ImportError and FileNotFoundError exceptions are caught using the as keyword, and their respective details are assigned to the variables err and err2. This allows for clearer error messages and better debugging.
Similar Reads
python class keyword In Python, class keyword is used to create a class, which acts as a blueprint for creating objects. A class contains attributes and methods that define the characteristics of the objects created from it. This allows us to model real-world entities as objects with their own properties and behaviors.S
1 min read
Python Keywords Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read
Python in Keyword The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary.Example:Pythons = "Geeks for geeks" if "for" in s: print("found") else: print("not found")
3 min read
is keyword in Python In programming, a keyword is a âreserved wordâ by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Py
2 min read
Keyword Module in Python Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are una
2 min read
Keywords in Python | Set 2 Python Keywords - Introduction Keywords in Python | Set 1 More keywords:16. try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in "try" block is checked, if there is any type of error, except block is executed. 17. except : As expl
4 min read