Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Identifiers

3.3

Identifiers

A program constantly refers to things — a variable that holds marks, a function that computes an average, or some other entity defined in the code. Each of these things needs a name, and in programming such a name is called an identifier. An identifier is simply the name you invent to identify a variable, a function, or any other entity in your program, so that you can refer to it later.

Python does not allow names to be formed arbitrarily. The rules for naming an identifier are:

  • The name must begin with an alphabet — uppercase or lowercase — or with the underscore sign (_). After this first character, any combination of the characters a–z, A–Z, 0–9 and the underscore may follow. A direct consequence of this rule: an identifier can never start with a digit. marks1 is valid, but 1marks is not.
  • The name can be of any length. There is no limit imposed by the language, although it is preferred to keep names short and meaningful — long enough to convey purpose, short enough to type comfortably.
  • The name must not be a keyword or reserved word (the words listed in the keyword table of this chapter). Those words already have a fixed meaning to the interpreter and cannot double as names.
  • Special symbols such as !, @, #, the dollar sign and % cannot appear anywhere in an identifier. The underscore is the only permitted symbol.

Beyond legality, there is the question of quality. A valid name is not automatically a good name. Consider the task of finding the average of the marks a student obtained in three subjects — Maths, English and Informatics Practices (IP). One could legally name the variables a, b, c or A, B, C, but such single letters give no clue about the data each variable refers to. Far better choices are names that describe the contents:

avg = (marksMaths + marksEnglish + marksIP)/3

Here marksMaths, marksEnglish and marksIP immediately tell a reader which subject's marks each variable holds, and avg announces that it stores the computed average. Anyone reading this single line — including you, weeks after writing it — understands the computation without any additional explanation. That is the real purpose of meaningful identifiers: a program is read far more often than it is written, and self-explanatory names make the reading effortless.

Tip

When choosing a name, describe the data, not the position. marksIP beats c every time. If a name needs two or more words, run them together with a capital at each new word (as in marksEnglish) or join them with underscores — both follow the naming rules. …