Section 2.3 Variable names and keywords
Programmers generally choose names for their variables that are meaningful and document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they cannot start with a number. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you’ll see why later).
The underscore character ( _ ) can appear in a name. It is often used in names with multiple words, such as
my_name or
airspeed_of_unladen_swallow. Variable names can start with an underscore character, but we generally avoid doing this unless we are writing library code for others to use.
If you give a variable an illegal name, you get a syntax error when you try to execute the code.
Activity 2.3.1.
Click the portion of the variable names that cause syntax errors.
Remember that variables cannot start with a number. If you’re stuck, look at the list of keywords below.
76trombones = "big parade"
more@ = 1000000
class = "Advanced Theoretical Zymurgy"
The variable name
76trombones is illegal because it begins with a number. The name
more@ is illegal because it contains an illegal character, @. But what’s wrong with
class?
It turns out that
class is one of Python’s
keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.
Python reserves 33 keywords:
and del from None True
as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return
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.
Activity 2.3.2.
Which of the following is
not a legal variable name?
-
_a1
-
You can use an underscore as the first character in a variable name
-
my_name
-
You can use an underscore between words in a variable name.
-
amountOfStuff
-
You can use both uppercase and lowercase letters in a variable name.
-
BMP
-
You can use only uppercase letters in a variable name.
-
1A
-
You can’t use a digit as the first letter in a variable name.
Activity 2.3.3.
Which of the following is
not a legal variable name?
-
_my_name
-
This is legal, but you don’t usually start a variable name with an underscore.
-
my name
-
You can’t have a space in a variable name.
-
myname
-
This may be hard to read, but it is legal.
-
myName
-
Since you can’t have spaces in names, one way to make variable names easier to read is to use camel case (uppercase the first letter of each new word).
-
my_name
-
Since you can’t have spaces in names, one way to make variable names easier to read is to use an underscore between two words.
You have attempted
of
activities on this page.