Python Identifiers
Python · Getting Started
Theory
An identifier is any name you create: a variable, function, class or module name. The rules are strict: it must start with a letter or an underscore, may then contain letters, digits and underscores, cannot contain spaces or symbols like - or $, and cannot be a keyword. Identifiers are case-sensitive, so age, Age and AGE are three different names. The string method 'total_sales'.isidentifier() checks the spelling rules (it does not check for keywords).
Beyond the rules there are conventions from PEP 8 that every Python programmer follows: snake_case for variables and functions (total_sales), PascalCase for classes (SalesReport), UPPER_CASE for constants (MAX_ROWS), and a leading underscore (_hidden) to signal 'internal, please do not touch'. Names surrounded by double underscores, like __init__, are reserved for Python's special methods.
Why we use it
Clear, valid names make code self-explaining: monthly_revenue tells the reader far more than x2. Knowing the rules prevents SyntaxErrors, and following the conventions makes your code look familiar to every other Python developer.
When to use it
Pick descriptive snake_case names for variables and functions and PascalCase for classes. Use single letters only for short loop counters (i, j). Avoid names that differ only by case, and avoid reusing built-ins such as list, dict or id.
How it works
- You choose a name, e.g. 2nd_place
- Does it start with a letter or underscore? Yes: Check the remaining characters. No: SyntaxError: invalid name.
- Only letters, digits and underscores after that? Yes: Check it is not a keyword. No: SyntaxError: invalid name.
- Is it a keyword like class or for? Yes: SyntaxError: reserved word. No: Valid identifier.
- Name can be assigned, e.g. total_sales = 100
Syntax
variable_name
_private
ClassNameExample
valid_name = 1
_hidden = 2
print(valid_name, _hidden)Key points
- Must start with a letter or underscore, never a digit
- Cannot contain spaces, hyphens or symbols like $ and @
- Case-sensitive: age and Age are different identifiers
- Convention: snake_case for variables, PascalCase for classes, UPPER_CASE for constants
- A leading underscore signals an internal name