Python program to check if a string is a valid keyword or not?

Defining a Keyword

In programming, keywords are the "reserved words" of the language, which convey special meaning to the interpreter. It can be a command or a parameter. Keywords cannot be used as variable names in program fragments. Keywords in Python: The Python language also reserves some keywords that convey special meaning. This knowledge is a necessary part of learning this language. The following is a list of keywords registered by python.

In Python, keywords are predefined reserved words that have specific meanings and cannot be used as variable names or identifiers. Python has a total of 35 keywords, and it is essential to know if a given string is a valid keyword or not.

Here's a Python program to check if a string is a valid keyword or not: 

 

import keyword

def is_valid_keyword(string):
    if keyword.iskeyword(string):
        print(f"{string} is a valid keyword")
    else:
        print(f"{string} is not a valid keyword")

# example usage
is_valid_keyword("if") # output: if is a valid keyword
is_valid_keyword("hello") # output: hello is not a valid keyword

The program uses the keyword module in Python, which provides a function iskeyword() to check if a given string is a valid keyword or not.

The is_valid_keyword() function takes a string as input and checks if it is a valid keyword or not using the iskeyword() function. If the string is a valid keyword, it prints a message saying so, and if not, it prints a message saying that the string is not a valid keyword.

In the example usage, we pass two strings "if" and "hello" to the is_valid_keyword() function. The first string "if" is a valid keyword, so the function outputs "if is a valid keyword". The second string "hello" is not a valid keyword, so the function outputs "hello is not a valid keyword".

Submit Your Programming Assignment Details