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

10 Aug, 2021
Defining a Keyword
In programming, a keyword is a “reserved word” by the language which 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.Keywords in Python:  Python language 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 in its language defines an inbuilt module “keyword” which handles certain operations related to keywords. A function “iskeyword()” checks if a string is a keyword or not. Returns true if a string is a keyword, else returns false. 
Python
#Instead of writing this massive Python code#we can also code this in a different way #Python code to demonstrate working of iskeyword() # importing "keyword" for keyword operationsimport keywordimport keyword# initializing strings for testing while putting them in an arraykeys = ["for", "while", "tanisha", "break", "sky","elif", "assert", "pulkit", "lambda", "else", "sakshar"] for i in range(len(keys)):     # checking which are keywords    if keyword.iskeyword(keys[i]):        print(keys[i] + " is python keyword")    else:        print(keys[i] + " is not a python keyword")
Output:  
for is a python keyword
geeksforgeeks is not a python keyword
elif is a python keyword
elseif is not a python keyword
nikhil is not a python keyword
assert is a python keyword
shambhavi is not a python keyword
True is a python keyword
False is a python keyword
akshat is not a python keyword
akash is not a python keyword
break is a python keyword
ashty is not a python keyword
lambda is a python keyword
suman is not a python keyword
try is a python keyword
vaishnavi is not a python keyword
 
How to print a list of all keywords
Sometimes, remembering all the keywords can be a difficult task while assigning variable names. Hence a function “kwlist()” is provided in the “keyword” module which prints all the 33 python keywords. 
Python
#Python code to demonstrate working of iskeyword() # importing "keyword" for keyword operationsimport keyword # printing all keywords at once using "kwlist()"print ("The list of keywords is : ")print (keyword.kwlist)
Output:  
The list of keywords is : 
['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']
   
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | How to check if a string is a valid keyword in Python? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ns5nZG1rV-M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Next Articles:  
Keywords in Python | Set 1
Keywords in Python | Set 2
This article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
TanishaTomar
punamsingh628700
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?