Python Keywords

Keywords in Python are reserved words that can be used as a variable name, function name or any other identifier. Number of keywords might change in different python versions. There are 35 keywords in Python 3.10.4

List of Python Keywords:

'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'

Since the keywords for a specific version might change, you can always get a list of keywords using below code:

import keyword

keywords_list = keyword.kwlist
print('Total No. Of Keywords: ', len(keywords_list))
print('All Keywords: ',keywords_list)

##output will be 
Total No. Of Keywords:  35
All Keywords:  ['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']

Soft Keywords:

Some identifiers are only reserved under specific contexts. These are known as soft keywords. The identifiers match, case and _ can syntactically act as keywords in contexts related to the pattern matching statement, but this distinction is done at the parser level, not when tokenizing. As soft keywords, their use with pattern matching is possible while still preserving compatibility with existing code that uses match, case and _ as identifier names

import keyword

keywords_list = keyword.softkwlist
print('Total No. Of Soft Keywords: ', len(keywords_list))
print('All Soft Keywords: ',keywords_list)

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

#how to check if a string is a reserved keyword or not
import keyword

s = 'while'

if keyword.iskeyword(s):
    print(s,' is a reserved keyword')
else:
    print(s,' is a not a reserved keyword')

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

#how to check if a string is a soft keyword or not
import keyword

s = 'match'

if keyword.issoftkeyword(s):
    print(s,' is a soft keyword')
else:
    print(s,' is a not a soft keyword')

Keywords In Detail

Value Keywords: True, False, None

True: This keyword is used to represent a boolen true value, is a statement is true
False: This keyword is used to represent a boolen false value, if a statement is false
None: This is a special constant that is used to represent a null value or void.

Leave a Comment

Share this