Click for Python keywords Part 2
Types of Python Keywords
Now continue Python keywords tutorial, In previous tutorial we learned about how Python keywords divided into different categories. We already learned Value keywords, Operator keywords, Control flow keywords and Iteration keywords. Now continue with rest of the keywords:
Structure Keywords in Python
def, class, pass, lambda
are the structure keywords in Python.
def keyword
def keyword is used to create or define a function. def is short for ‘define’. This is equivalent to a function in JavaScript. For example:
Code:
def my_function():
print('Creating First Function')
my_function()
Output:
Creating First Function
Here we used def keyword; after that, write function name, my_function
and in the last line we call this function.
class keyword
class keyword is used to create or define a class. Classes are very useful in object-oriented programming. class is like an object constructor; we can create objects by class. For example:
Code:
class FirstClass:
name = "Python"
language = FirstClass()
print(language.name)
Output:
Python
Here we create a class named FirstClass
. And with the help of this class, we created an object named language.
pass keyword
We use pass keyword when we want to leave an empty statement. Normally we cannot leave empty statements in loops, functions, or in class. So we use pass keyword. For example:
Code:
x = 10
if x > 5:
print(x)
Output:
IndentationError: expected an indented block after 'if' statement on line 2
Here we didn’t provide any statement under if condition. It is necessary to provide any statement under if condition. So either we provide any statement or we can use pass keyword.
Code:
x = 10
if x > 5:
pass
print(x)
Output:
10
So we used pass keyword when we wanted an empty statement or wanted to update later.
lambda keyword
lambda keyword is used to define a function that doesn’t have a name, or, we could say, it is used to create small anonymous functions.
A lambda function can take any number of arguments but can only have one expression. For example:
Code:
num = lambda a : a + 10
print(num(10))
Output:
20
So these are the structure keywords in Python.
Context Keywords in Python
with, as
are the context keywords in python
with keyword
with keyword is used in exception handling. It is also very helpful in file I/O (input output). When we want to open a file and do some work on that file, and after that we want to make sure that file was closed correctly, then we use with
keyword as context manager. For example:
Code:
with open('python.txt', 'w') as file:
file.write('python programming')
This is just syntax, how we write our code; this won’t run because we don’t have any file like python.txt
as keyword
as keyword is used to create an alias in Python. Sometimes when we import modules that have a long name, or maybe you already have a variable name, the same as the module name. In such cases, we can use as
keyword to create the alias. For example:
Code:
import keyword
print(len(keyword.kwlist))
Now in this example, we import keyword
module and try to print the number of keywords. Now we are going to try to change the name of this module.
Code:
import keyword as word
print(len(word.kwlist))
Output:
35
Now we changed the module name. And now we can use this module with a new name.
So these are the context keywords in Python.
Returning Keywords in Python
return, yield
are the returning keywords in Python.
return keyword
The return keyword is used to end the execution of the function and return the result. For example:
Code:
def first_function(num):
return num + 10
print(first_function(20))
Output:
30
So we get a return statement in the output.
yield keyword
yield keyword is same as return with some difference. The yield keyword is used to return a list of values from a function. So basically, yield keyword is used to create generator function.
The main difference between yield and return is that the return keyword stops further execution of the function. While yield continues to the end of the function. For example:
Code:
def language():
yield 'Python'
yield 'Java'
yield 'PHP'
values = language()
print(next(values))
print(next(values))
print(next(values))
Output:
Python
Java
PHP
So we get a list of values in output. One value for each yield.
So these are the return keywords in Python.
Import Keywords in Python
Two keywords regarded as import keywords in Python: import, from
import keyword
The import keyword is used to import a module for use in your Python program. For example:
Code:
import keyword
import os
Here we are importing keyword
modules and os
modules. Python has lots of modules, which we can import into our code according to their uses.
from keyword
from keyword is used with import keyword. By using from, we can import something specific from a module.
Code:
import keyword
from keyword import kwlist
print(kwlist)
Output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Here we import kwlist from keyword
module, which prints the name of all keywords in Python.
Exception Handling Keywords
Five keywords regarded as exception handling keywords in Python: try, except, raise, finally, assert
try keyword
try keyword is used with exception handling. We used try in our program if we thought our program might show an error. So we used several other functions with try. So if an error raises those other defined functions, try to handle that error. There are three other keywords that work with try: except, else, finally. If we didn’t use any one of them keyword with try, our program will not work.
except keyword
except keyword is worked with try block. We define a statement in the except block, so if an error is raised, the code in the except block shows how to handle that error. A single try block could have more than one except block.
finally keyword
finally
keyword is worked with try
block. We used finally block after try block. Whatever we write in finally
will execute.
assert keyword
assert keyword is used for debugging code. assert keyword work with assertion. assertion is a process used to check your code in during the debugging process. If your assumption remains True it does nothing, but if it is False, then it raises an AssertionError.
raise keyword
raise
keyword is used to raise an error. You can manually raise an exception by writing your exception after raise
keyword.
So these are the exception-handling keywords in Python.
Asynchronous Programming Keywords in Python
async, await are the asynchronous programming keywords in Python.
async keyword
async keyword is used with asynchronous function. We can make a function asynchronous by adding async before the def keyword.
await keyword
await keyword also used in asynchronous function.
Variable Handling Keywords in Python
del, global, nonlocal are the variables handling keywords in Python.
del keyword
del keyword is used to delete objects in Python. We can delete variable names, lists, tuples, and all other objects. It is recommended to delete the unnecessary object in your code to free up memory.
Code:
name = 'Python'
print(name)
del name
print(name)
Output:
Python
NameError: name 'name' is not defined
So this is how we delete variables using del
keyword.
global keyword
global
keyword is used to create global variables inside the local scoop. So with the help of global keywords, we can create a global variable inside the function.
nonlocal keyword
nonlocal keyword is the same as a global keyword, but a nonlocal keyword does not work with global and local variables. It allows us to modify variables from a different scope. nonlocal keyword worked with parent scope, mostly used in nested functions.
Conclusion
This is the end of the Python keywords tutorial. Keywords are very important in Python. You don’t have to remember all the keyword names or their functions, but if you had a basic idea of what keywords do in Python, it would be very helpful in programming.
End of Python Keyword Tutorial
One thought on “Python Keywords (Part 3): Types And Uses Of Keywords In Python”