Python program to check if a given string is Keyword or not

Given a string, write a Python program that checks if the given string is keyword or not.

  • Keywords are reserved words which cannot be used as variable names.
  • There are 33 keywords in Python programming language.(in python 3.6.2 version)

Examples:

Input: str = "geeks"
Output: geeks is not a keyword

Input: str = "for"
Output: for is a keyword

We can always get the list of keywords in the current Python version using kwlist method in keyword module.



filter_none

edit
close

play_arrow

link
brightness_4
code

# import keyword library
import keyword
  
keyword_list = keyword.kwlist
print("No. of keywords present in current version :",
                                   len(keyword_list))
  
print(keyword_list)

chevron_right


Output:

No. of keywords present in current version : 33
[‘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’]

Below is the Python code to check if a given string is Keyword or not:

filter_none

edit
close

play_arrow

link
brightness_4
code

# include keyword library in this program
import keyword
  
# Function to check whether the given 
# string is a keyword or not 
def isKeyword(word) :
  
    # kwlist attribute of keyword
    # library return list of keywords
    # present in current version of
    # python language.
    keyword_list = keyword.kwlist
  
    # check word in present in
    # keyword_list or not.
    if word in keyword_list :
        return "Yes"
    else :
        return "No"
  
  
# Driver Code
if __name__ == "__main__" :
  
    print(isKeyword("geeks"))
    print(isKeyword("for"))

chevron_right


Output:

No
Yes


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.