2.6. Updating Variables¶
A common pattern in assignment statements is an assignment statement that updates a variable, where the new value of the variable depends on the old value of the variable.
x = x + 1
As a math equation this doesn’t make a lot of sense (unless x is
\(\infty\)), but this works in programming beause assignment is not
equality. According to the assignment
statement syntax pattern, the computer will first
evaluate the expression on the right, x + 1
, and then assign that value
to x
. So the statement means “get the current value of x
, add 1 to it,
and then update x
with the new value.”
If x doesn’t exist yet and has no value this staement will give you an error. Python will evaluate the right side and be unable to proceed. Try this:
What’s missing? Before you can update a variable, you have to initialize it, usually with a simple assignment:
Updating a variable by adding or subtracting 1 is very common in programming, and so those updates have special names:
Definition
Updating a variable by adding 1 is called an increment, and subtracting 1 is called a decrement.
Check your understanding
Q-1: If each of the following lines of code are run one after the other, what
will the value of x
be after each line? Write the value x
holds
after each line executes in the blank to the right of the line.
x = 12
y = 34
z = 56
x = x + y
z = x
x = y