Game Development Reference
In-Depth Information
Storing Values in Variables
When we program, we will often want to save the values that our expressions evaluate to
so we can use them later in the program. We can store values in variables .
Think of variables like a box that can hold values. You can store values inside variables
with the = sign (called the assignment operator ). For example, to store the value 15 in a
variable named "spam", enter spam = 15 into the shell:
>>> spam = 15
>>>
You can think of the variable like a
box with the value 15 inside of it (as
shown in Figure 2-4). The variable
name "spam" is the label on the box (so
we can tell one variable from another)
and the value stored in it is like a small
note inside the box.
When you press Enter you won't see
anything in response, other than a
blank line. Unless you see an error
message, you can assume that the
instruction has been executed
successfully. The next >>> prompt will
appear so that you can type in the next instruction.
Figure 2-4: Variables are like boxes that can hold values in them.
This instruction (called an assignment statement ) creates the variable spam and
stores the value 15 in it. Unlike expressions, statements are instructions that do not
evaluate to any value, which is why there is no value displayed on the next line in the shell.
It might be confusing to know which instructions are expressions and which are
statements. Just remember that if the instruction evaluates to a single value, it's an
expression. If the instruction does not, then it's a statement.
An assignment statement is written as a variable, followed by the = equal sign, followed
by an expression. The value that the expression evaluates to is stored inside the variable.
The value 15 by itself is an expression. Expressions made up of a single value by itself are
easy to evaluate. These expressions just evaluate to the value itself. For example, the
expression 15 evaluates to 15!
Remember, variables store values, not expressions. For example, if we had the statement,
spam = 10 + 5 , then the expression 10 + 5 would first be evaluated to 15 and then
the value 15 would be stored in the variable, spam .
Search WWH ::




Custom Search