2.8. 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. If you do, remember
that case matters. Bruce
and bruce
are different variables.
Caution
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). This list is current as of Python
version 3.5:
and |
as |
assert |
async |
await |
break |
class |
continue |
def |
del |
elif |
else |
except |
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.
Check your understanding
- True
- - The + character is not allowed in variable names.
- False
- - The + character is not allowed in variable names (everything else in this name is fine).
True or False: the following is a legal variable name in Python: A_good_grade_is_A+
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.