What is a keyword in Python: Definition
Keywords are built-in reserved words that come with Python language. You cannot use the reserved keyword as an identifier or a variable. Keywords in Python are case sensitive.
How many keywords are there in python
For the latest Python 3.8 version, the total keywords are 35.
Python code to know the total count/number of keywords
import keyword
a = keyword.kwlist
print("Total number of keywords in Python: ",len(a))
Python code to print the list and names of all keywords in Python
Code:
import keyword
list_python_keywords = keyword.kwlist
for i in range(0, len(list_python_keywords)):
print(i+1, " ", list_python_keywords[i])
To implement the above code we have imported the Python keyword module. The keyword module contains a list of all the keywords used in the current version of Python.
List and names of all Keywords in Python
False None True and as assert async await 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
Python code to check a string|variable|identifier is a reserved keyword or not
Code:
import keyword
keyword_name = input("Enter keyword to be checked: ")
if keyword.iskeyword(keyword_name):
print(keyword_name, " is a reserved or valid keyword.")
else:
print(keyword_name, " is not a reserved or valid keyword.")
Output:
Enter keyword to be checked: else Yes, else is a reserved or valid keyword.
Python Keyword module
This module allows a Python program to determine if a string is a keyword.
- keyword.iskeyword(keyword_to_be_checked)
- Return true if keyword_to_be_checked is a Python keyword.
- keyword.kwlist
- It lists all the keywords in the sequence for the current Python version installed in the system.