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 unaware of all the keywords of Python you can use this module to retrieve this information. Also, it helps you to check whether a word is a keyword or not just by using its functions on Python shell mode.
The functions of this module are:
- keyword.iskeyword(parameter)
This function returns True if the parameter passed is a Python keyword else returns False. The parameter can be a string or a variable storing a string. It accordingly compares the parameter with Python keywords defined in the language and returns the output.Example:
# Program to check whether a given
# word is a Python keyword or not
import
keyword
s
=
"if"
t
=
"in"
u
=
"Lazyroar"
# using iskeyword() function to check
print
(s,
"is a keyword in Python:"
,
keyword.iskeyword(s))
print
(
"lambda is a keyword in Python:"
,
keyword.iskeyword(
"lambda"
))
print
(
"print is a keyword in Python:"
,
keyword.iskeyword(
"print"
))
print
(t,
"is a keyword in Python:"
,
keyword.iskeyword(t))
print
(u,
"is a keyword in Python:"
,
keyword.iskeyword(u))
Output:
if is a keyword in Python: True lambda is a keyword in Python: True print is a keyword in Python: False in is a keyword in Python: True Lazyroar is a keyword in Python: False
As you can see from the above example that the value of variable s and t is a keyword in Python, thus the function returns True. Similarly, the string Lazyroar is not a keyword, thus the function returns False.
- keyword.kwlist
This is a predefined variable of keyword module that stores all the keywords of Python. Thus it can be used to display all the keywords of Python just by calling it.Example:
# Program to display the list of Python keywords
# importing keyword module
import
keyword
# using keyword.kwlist to display the list of keywords
print
(keyword.kwlist)
Output:
[‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘exec’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘not’, ‘or’, ‘pass’, ‘print’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
Note: keyword.kwlist is not a function, hence no parenthesis are used with it. kwlist is a variable defined previously in the keyword module.