Skip to main content

Section 2.4 Variable Names, Keywords, and Constants

Subsection 2.4.1 Variable Names and Keywords

Variable names can be arbitrarily long. They can contain both letters and digits, but they have to begin with a letter or an underscore. Although it is legal to use uppercase letters, by convention we don’t—except for constants. If you do, remember that case matters. Bruce and bruce are different variables.

Warning 2.4.1.

Variable names can never contain spaces.
The underscore character ( _) can also appear in a name. It is often used in names with multiple words, such as my_name or price_of_tea_in_china. There are some situations in which names beginning with an underscore have special meaning, so a safe rule for beginners is to start all names with a letter.
If you give a variable an illegal name, you get a syntax error. In the example below, each of the variable names is illegal.
76trombones = "big parade"
  more$ = 1000000
  class = "Computer Science 101"
76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an illegal character, the dollar sign. But what’s wrong with class?
It turns out that class is one of the Python keywords. Keywords define the language’s syntax rules and structure, and they cannot be used as variable names. Python has thirty-something keywords (and every now and again improvements to Python introduce or eliminate one or two):
Table 2.4.2.
and as assert break class continue
def del elif else except exec
finally for from global if import
in is lambda nonlocal not or
pass raise return try while with
yield True False None
You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.

Checkpoint 2.4.3.

    True or False: the following is a legal variable name in Python: A_good_grade_is_A+
  • True
  • - The + character is not allowed in variable names.
  • False
  • - Correct. The + character is not allowed in variable names (everything else in this name is fine).

Subsection 2.4.2 Constants

Sometimes you will want to use names for variables whose values should never change, for example the number of days in a week, or the acceleration of gravity, or a discount percentage. These are called constants.
In Python, by convention, when you use all upper case letters to name a variable, this tells people who read your code that they should leave the values alone and never change them. For example:
DAYS_PER_WEEK = 7
EARTH_GRAVITY = 9.8
POUNDS_PER_KILOGRAM = 2.2046
DISCOUNT_PERCENT = 0.035
Using constants makes code more readable. Someone might not know what the number 2.2046 represents, but they will understand what kind of calculation is meant when multiplying by POUNDS_PER_KILOGRAM.
Note: These are not true constants—programmers can change the values anyway, but it’s considered extremely bad form to do so!