Python Keywords

Python Keywords are set of reserved words that have specific meanings and purposes and can’t be used for anything but those specific purposes. These keywords can't be used as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.

In Python, keywords are case sensitive. There are 35 keywords in Python 3.8.  All the keywords except True, False and None are in lowercase.

Print was also a keyword in Python 2 but it is not a keyword in Python 3+ as it is a built-in function .

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

Ways to Identify Keywords:

We can get a list of available keywords by using help().

help("keywords")

Output:

Here is a list of the Python keywords.  Enter any keyword to get more help.

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

We can use keyword module for working with Python keywords in a programmatic ways. The keyword module in Python provides two helpful members for dealing with keywords

1. kwlist : It provides a list of all the Python keywords for the version of Python you’re running.

import keyword
print(keyword.kwlist)

Output:

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

len(keyword.kwlist)

Output: 33

2. iskeyword(): It provides a handy way to determine if a string is also a keyword.

import keyword

keys = ["for", "while", "Shiksha", "break", "Devanshi"]
  
for i in range(len(keys)):
    if keyword.iskeyword(keys[i]):
        print(keys[i] + " is python keyword")
    else:
        print(keys[i] + " is not a python keyword")

Output:

for is python keyword
while is python keyword
Shiksha is not a python keyword
break is python keyword
Devanshi is not a python keyword

Tags