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. If you do, remember that case matters. Bruce
and bruce
are different variables!
However, 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
. If you give a variable an illegal name, you get a syntax error. In the example below, each of the variable names is illegal.
1st_num
is illegal because it does not begin with a letter. second num is illegal because it contains the space character.
third.num
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). All of the following words can not be used to name variables:
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 |