Home »
Python
Check whether the given string is a keyword or not using keyword module
Python keyword module example: Here, we are going to learn how to check whether the given string is a keyword or not using keyword module in Python?
Submitted by Bipin Kumar, on November 01, 2019
In this program, a string will be given by the user and we have to check whether it is a keyword in Python or not. To do this task in Python we will use a module which name is the keyword. Before going to do this task we will see a program that will return all keywords of Python programming language.
Python program to print all keyword
# importing the module
import keyword
# getting the list of all keywords
List_of_key=keyword.kwlist
# printing the number of keywords
print("No of keyword in Python: ",len(List_of_key))
#To print lists of all keyword present in Python.
print("List of keyword:",List_of_key)
Output
No of keyword in Python: 33
List of keyword: ['False', 'None', 'True', 'and', 'as', 'assert', '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']
Note:
- Here, we have seen that the total keyword in Python language is 33.
- Python does not allow us to use the keyword as a variable in the program.
Algorithm to check given string is a keyword or not?
- Initially, we will include the keyword module in Python by using the import function.
- Take the input string from the user.
- Take a list of all keyword in a variable by using kwlist() function from the module keyword.
-
Check the given string is lies in the above-created list or not by using the keyword of Python.
- If it lies in the list then print the given string is a keyword in the Python programming language.
- If it does not lie in the list then print the given string is not a keyword in the Python programming language.
So, let's start writing the python program by the implementation of the above algorithm,
Python program to check whether given string is a keyword or not
# importing the module
import keyword
# input a string
str=input("Enter a string: ")
# getting a list of all keywords
List_of_key=keyword.kwlist
# checking whether given string is a keyword or not
if str in List_of_key:
print("String {} is a keyword.".format(str))
else:
print("String {} is not a keyword.".format(str))
Output
RUN 1:
Enter a string: includehelp
String includehelp is not a keyword.
RUN 2:
Enter a string: try
String try is a keyword.
RUN 3:
Enter a string: nonlocal
String nonlocal is a keyword.