An identifier is simply the name you choose to identify a variable, function, class, module, or package in your Python code. Choosing clean, descriptive identifiers not only makes your code compliant with university BCA exams, but also ensures that your software is maintainable by software engineering teams across the world.
To write valid identifiers that compile without error, you must follow these 5 mandatory rules:
• Rule 1: Allowed Characters Only: An identifier can contain lowercase letters (a-z), uppercase letters (A-Z), digits (0-9), and the underscore (_).
• Rule 2: Cannot Start with a Digit: An identifier must begin with a letter or an underscore. It cannot begin with a number (e.g. 1st_rank is INVALID, but rank_1 is VALID).
• Rule 3: Strictly Case-Sensitive: Python distinguishes between uppercase and lowercase. age, Age, and AGE are three completely different identifiers with separate memory addresses.
• Rule 4: Keywords Cannot Be Used: You cannot name an identifier with any of the 35 reserved Python keywords (e.g. for, class, return).
• Rule 5: No Special Symbols or Spaces: Symbols like $, @, %, !, -, or white spaces are illegal.
| Identifier | Status | Reason |
|---|---|---|
student_name |
VALID | Uses letters and underscore. Standard snake_case convention. |
_database_conn |
VALID | Starts with an underscore (often indicates internal/private use). |
totalMarks2024 |
VALID | Alphanumeric; digits are at the end, not at the beginning. |
99_balloons |
INVALID | SyntaxError: Cannot begin with a number. |
emp-salary |
INVALID | SyntaxError: Contains a hyphen (minus operator), not an underscore. |
user name |
INVALID | SyntaxError: Contains a space. Use user_name instead. |
while |
INVALID | SyntaxError: while is a reserved Python keyword. |
Writing valid code is not enough; writing Pythonic code requires following PEP 8 (the official Style Guide for Python Code):
• Variables & Functions: Use snake_case (all lowercase with words separated by underscores): calculate_total_bill(), user_id.
• Classes: Use PascalCase (CapitalizedWords): StudentReport, DatabaseConnection.
• Constants: Use SCREAMING_SNAKE_CASE (ALL_CAPS): MAX_RETRIES = 5, PI = 3.14159.
• Private Attributes: Prefix with a single leading underscore (_internal_counter) or double underscore for name mangling (__private_key).
str.isidentifier()Did you know Python has a built-in method to test if a string qualifies as a valid identifier? Let us test it:
# Programmatic validation of identifiers
test_names = ["user_1", "1user", "def", "_total", "user$name"]
for name in test_names:
is_valid = name.isidentifier()
print(f"'{name}': is_identifier={is_valid}")
'user_1': is_identifier=True
'1user': is_identifier=False
'def': is_identifier=True # (Valid identifier pattern, but blocked as keyword!)
'_total': is_identifier=True
'user$name': is_identifier=False
__init__, __str__, __len__). These are reserved by Python for magic/special methods in Operator Overloading and OOP.