What is keyword.iskeyword() in Python?

Overview

Python is a high-level programming language that provides functionalities for several operations. The keyword module comes with various methods to manipulate keywords.

The function keyword.iskeyword() checks if a string is a valid keyword in Python.

Syntax

keyword.iskeyword(x)

Parameters

  • x: This is the specified string that is passed as a parameter to check if it is a valid keyword or not. This parameter is required.

Return value

This function returns the Boolean value True if x is a valid keyword. Otherwise, it returns False.

Example

#import module
import keyword
#intialize test strings
string1 = 'import'
string2 = 'no'
string3 = 'from'
string4 = 'val'
string5= 'as'
#check for valid keywords
print(string1,': ',keyword.iskeyword(string1))
print(string2,': ',keyword.iskeyword(string2))
print(string3,': ',keyword.iskeyword(string3))
print(string4,': ',keyword.iskeyword(string4))
print(string5,': ',keyword.iskeyword(string5))

Explanation

  • Line 2: We import the keyword module.
  • Lines 5 to 9: We initialize test strings. Some are reserved keywords in Python.
  • Lines 12 to 16: We test to see whether the strings are valid keywords or not.

In the output, the test string is first printed. True is printed if it is a valid keyword. Otherwise, False is printed.

Free Resources