write a function that takes a string as parameter, return true if it’s a valid variable name, false otherwise. You can use keyword module’s iskeyword() to determine if a string is keyword.

Respuesta :

Answer:

The solution code is written in Python 3:

  1. import keyword  
  2. def checkValidVariable(string):
  3.    if(not keyword.iskeyword(string)):
  4.        return True  
  5.    else:
  6.        return False  
  7. print(checkValidVariable("ABC"))
  8. print(checkValidVariable("assert"))

Explanation:

Firstly, we need to import keyword module so that we can use its iskeyword method to check if a string is registered as Python keyword (Line 1).

Next, we create a function checkValidVariable that takes one input string (Line 3). Within the function body, we use iskeyword method to check if the input string is keyword. Please note the "not" operator is used here. So, if iskeyword return True, the True value will be turned to False by the "not" operator or vice versa (Line 4-5).

We test the function by passing two input string (Line 9-10) and we shall get the sample output as follows:

True

False