Sitemap
Ravi kumar

Ravi kumar

Learning going on...

isIdentifier( ) Function work proper in python?

1 min readJan 13, 2024

What is Identifier ?

Identifiers are names given to various programming elements such as variables, functions, classes, modules, etc. in Python. various names are used to uniquely identify various programme parts.

Rules for Identifiers

  1. Case Sensitivity: Python is case-sensitive. For example, myVar and myvar are distinct identifiers.
  2. Start with a Letter or Underscore (_): Identifiers must start with a letter (a-z, A-Z) or an underscore. They must not begin with a number.
  3. Consist of Letters, Digits, and Underscores: Identifiers can include the letters, digits (0–9), and underscores.
  4. Cannot be a Reserved Word: Identifiers cannot be a reserved word in Python. You cannot, for example, use if, else, for, and so on as identifiers.
  5. Cannot Contain Special Characters: Identifiers cannot contain special characters such as !, @, #, $, etc.

Note: isidentifier() is function to check the identifiers.

Get Ravi kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Example: Following Example are correct according to rule and isidentifier():

print("container".isidentifier())# "container" as a identifier
print("_a".isidentifier()) # "_a" is a identifier
print("2a".isidentifier()) # "2a" is a not identifier
print("if".isidentifier()) # "if" is a reserve keyword not a identifier.

isidentifier() function doesn’t work in case of keywords: When we we take reserve words as a identifier. It will return True i.e not correct according to rules.

Now, the correct code to find the valid identifier are given below

import keyword as key
identifier1='if'
identifier2='_if'
print( not key.iskeyword(identifier1) and identifier1.isidentifier())
print( not key.iskeyword(identifier2) and identifier2.isidentifier())

--

--