Skip to main content

Python Identifiers

In this tutorial, we will explore:

  • What identifiers are
  • Rules for defining identifiers
  • Valid and invalid examples
  • Naming conventions (underscore usage)

What is an Identifier?

In real life, we identify people using names. These names help us distinguish one person from another.

In Python

An identifier is a name used to identify variables, functions, classes, or other objects in a Python program.

What Can Be an Identifier?

An identifier can be:

  • Variable name
  • Function (method) name
  • Class name
  • Module name

Example

a = 10
  • a is the identifier
  • It is used to represent the value 10

Another Example

class Test:
pass
  • Test is a class name
  • It is also an identifier

Rules for Defining Python Identifiers

Just like naming a person involves some thought and convention, Python also has strict rules for naming identifiers.

Rule 1: Allowed Characters

Only the following characters are allowed:

  • Alphabets (a–z, A–Z)
  • Digits (0–9)
  • Underscore (_)

Valid Examples

cash = 10
total123 = 20
my_var = 30

Invalid Examples

ca$h = 10
@value = 20

Rule 2: Cannot Start with a Digit

An identifier must not begin with a number.

# following is valid
total123 = 10

# following is invalid
123total = 10 # ❌ Invalid

Rule 3: Case Sensitivity

Python is a case-sensitive language, which means, Uppercase and lowercase letters are treated differently.

Example

total = 10
Total = 20
TOTAL = 30

These are three different variables.

Rule 4: No Length Limit

Python does not impose any limit on identifier length.

Example

this_is_a_very_long_variable_name_used_for_demo_purpose = 10
print(this_is_a_very_long_variable_name_used_for_demo_purpose)

Rule 5: Cannot Use Reserved Words

Python has some predefined words called keywords.

Examples:

  • if
  • else
  • for
  • while

Invalid Example

if = 10 # ❌ Invalid

Valid Example

value = 10

Special Meaning of Underscore (_)

Identifiers using underscores have special conventions in Python.

1. Normal Variable
x = 10
2. Protected Variable (Single Underscore)
_x = 10
  • Convention: intended for internal use
  • Indicates "protected" usage
3. Private Variable (Double Underscore)
__x = 10
  • Stronger restriction
  • Used mainly in classes (name mangling)
4. Magic Variables (Double Underscore Both Sides)
__init__
__name__
  • Special predefined variables
  • Used internally by Python