Keyword Module in Python

In this tutorial, we will learn about the Keyword Module in Python, its uses and its implementation.

What is a Keyword?

A Python keyword is a special reserved word in Python which has a special meaning and is used to execute some specific operations.

Since a keyword is reserved in Python, we should keep in mind that we cannot simply use the keywords as a variable name.

Keywords in Python

At present, there are 34 keywords in Python. We should note that this number can vary with time and with the version of Python.
The 34 keywords are given as:

1.  None
2.  True
3.  and
4.  as
5 . assert
6 . async
7.  await
8.  break
9.  class
10.  continue
11.  def
12.  del
13.  elif
14.  else
15.  except
16.  finally
17.  for
18.  from
19.  global
20.  if
21.  import
22.  in
23.  is
24.  lambda
25.  nonlocal
26.  not
27.  or
28.  pass
29.  raise
30.  return
31.  try
32.  while
33.  with
34.  yield

The Keyword Module

A module is basically a Python program that contains a collection of similar types of functions, classes, variables, etc.

The keyword module in Python allows us to check if a given string is a keyword or not.
For this, we have to import the keyword module first.

import keyword

The following functions are used to check keywords after importing the keyword module.

Also, read: The yield keyword in Python

keyword.iskeyword(string)
We use this to check if a string is a keyword or not.

import keyword
keyword.iskeyword("yield")
keyword.iskeyword("CodeSpeedy")

Output

True
False

keyword.kwlist

We use this to check if a string is a keyword or not.

import keyword 
keyword.kwlist

We will get the following output for the above program:

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

Note: All codes are written in Python shell mode.

 

Leave a Reply

Your email address will not be published. Required fields are marked *