Computer Science · Ch 5 — Getting Started with Python
Identifiers
5.3
Identifiers
In programming languages, identifiers are the names used to identify a variable, a function, or any other entity in a program. Choosing them is not free-form — Python lays down precise rules.
Rules for naming an identifier in Python
- The name must begin with an uppercase letter, a lowercase letter, or an underscore
_. After the first character, any combination of the charactersa–z,A–Z,0–9and underscore may follow. A direct consequence: an identifier cannot start with a digit —marks1is legal,1marksis not. - It can be of any length, though it is preferred to keep identifiers short and meaningful.
- It must not be a keyword (any reserved word listed in Table 5.1).
- Special symbols are not allowed anywhere in an identifier — characters such as
!,@,#, the dollar sign,%and the like cannot appear in a name.
Why meaningful names matter
Identifiers are for the humans reading the program as much as for the interpreter. Consider computing the average of a student's marks in three subjects. Choosing the identifiers marks1, marks2, marks3 and avg — rather than a, b, c or A, B, C — makes the statement self-explanatory:
avg = (marks1 + marks2 + marks3)/3
Similarly, to compute the area of a rectangle, names such as area, length and breadth give clarity and readability that single letters cannot:
area = length * breadth
Checking the rules against examples
| Candidate name | Valid? | Reason |
|---|---|---|
total_marks | Yes | letters + underscore only |
_count | Yes | may begin with an underscore |