Skip to main content

Section 2.15 Updating Variables

One of the most common forms of reassignment is an update, where the new value of the variable depends on the old value. For example,
x = x + 1
In algebra, this is an impossible statement; a variable can’t be equal to itself plus one.
In Python, however, = is the assignment operator. x = x + 1 means: get the current value of x, add one, and then update x with the new value. The new value of x becomes the old value of x plus 1.
Remember that executing an assignment statement is a two-step process. First, Python always evaluates the expression on the right side of the =. Second, the variable name on the left-hand side will be assigned the resulting object. The fact that x appears on both sides does not matter. The semantics of the assignment statement makes sure that there is no confusion as to the result. The visualizer makes this very clear.

Checkpoint 2.15.1.

x = 6
x = x + 1
If you try to update a variable that doesn’t exist, you get an error because Python evaluates the expression on the right side of the assignment operator before it assigns the resulting value to the variable on the left. Before you can update a variable, you have to initialize it, usually with a simple assignment. In the above example, x was initialized to 6.
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement. Sometimes programmers also talk about bumping a variable, which means the same as incrementing it by 1.

Checkpoint 2.15.2.

    What is printed when the following statements execute?
    x = 12
    x = x - 1
    print(x)
    
  • 12
  • The value of x changes in the second statement.
  • -1
  • In the second statement, substitute the current value of x before subtracting 1.
  • 11
  • Yes, this statement sets the value of x equal to the current value minus 1.
  • Nothing. An error occurs because x can never be equal to x - 1.
  • Remember that variables in Python are different from variables in math in that they (temporarily) hold values, but can be reassigned.

Checkpoint 2.15.3.

    What is printed when the following statements execute?
    x = 12
    x = x - 3
    x = x + 5
    x = x + 1
    print(x)
    
  • 12
  • The value of x changes in the second statement.
  • 9
  • Each statement changes the value of x, so 9 is not the final result.
  • 15
  • Yes, starting with 12, subtract 3, then add 5, and finally add 1.
  • Nothing. An error occurs because x cannot be used that many times in assignment statements.
  • Remember that variables in Python are different from variables in math in that they (temporarily) hold values, but can be reassigned.

Checkpoint 2.15.4.

Construct the code that will result in the value 134 being printed.

Note 2.15.5.

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.