The name we give a variable, also called its
identifier, is subject to some important rules. Some of these rules are strict - Python will not accept names that do not follow these rules. These rules are part of the
syntax of Python. The syntax of a language is the rules for what are valid ways to write things in the language. Other rules for variable names are human conventions. Python will not enforce these rules, but you and other programmers reading your code may get confused.
Subsection 14.2.2 Naming Convention
Programmers generally choose names for their variables that are meaningful to the human readers of the program — they help the programmer document, or remember, what the variable is used for. To be meaningful, a name must clearly describe what a piece of information is to anyone reading the code, not just the author of the code.
Meaningful names are generally full words like
height
. Abbreviations are generally not meaningful to anyone other than the original author. If you are reading through code and see a variable
h
, that will likely not do anything to help you figure out what information it is holding. (The exception to this rule is representing values from a mathematical formula like
where
a
has a well-defined meaning.)
Oftentimes, you need multiple words to meaningfully describe a variable. Say you have a program that involves converting a height between inches and centimeters, within that program, the name
height
might be confusing. Is it referring to a value in inches? centimeters?
In cases like this, since you can’t have spaces in a variable name, you can either join words together by uppercasing the first letter of each new word like
heightInInches
(called
mixed-case or
camel-case because the capitals look like the humps of a camel) or use underscores between words like
height_in_inches
(called
snake-case).