Open In App
Related Articles

How to check if a string is a valid keyword in Python?

Like Article
Save Article
Report issue

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.

What is Keywords in Python

Python also reserves some keywords that convey special meaning. Knowledge of these is a necessary part of learning this language. Below is a list of keywords registered by Python

False, elif, lambda, None, else, nonlocal, True, except, not, and, finally, or, as, for, pass, assert, from, raise, break, global, return, class, if, try, continue, import, while, def, in, with, del is, yield

Python Program to Check if a String is a Keyword

Python in its language defines an inbuilt module keyword that handles certain operations related to keywords. iskeyword() checks if a string is a keyword or not. Returns true if a string is a keyword, else returns false.


# importing "keyword" for keyword operations
import keyword
# initializing strings for testing while putting them in an array
keys = ["for", "geeksforgeeks", "elif", "elseif", "nikhil",
        "assert", "shambhavi", "True", "False", "akshat",
        "akash", "break", "ashty", "lambda", "suman",
        "try", "vaishnavi"]
for i in range(len(keys)):
     # checking which are keywords
    if keyword.iskeyword(keys[i]):
        print(keys[i] + " is python keyword")
        print(keys[i] + " is not a python keyword")


for is python keyword
geeksforgeeks is not a python keyword
elif is python keyword
elseif is not a python keyword
nikhil is not a python keyword
assert is python keyword
shambhavi is not a python keyw...

Print a list of all keywords

Sometimes, remembering all the keywords can be a difficult task while assigning variable names. Hence, kwlist() function is provided in the keyword module which prints all the 33 python keywords.


# importing "keyword" for keyword operations
import keyword
# printing all keywords at once using "kwlist()"
print ("The list of keywords is : ")
print (keyword.kwlist)


The list of keywords is : 
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda...

Next Articles:  

Last Updated : 25 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads