This means get the current value of x, add one, and then update x with the new value. The new value of x is the old value of x plus 1. Although this assignment statement may look a bit strange, remember that executing assignment statements is a two-step process. First, evaluate the right-hand side expression. Second, let the variable name on the left-hand side refer to this new resulting object. The fact that x appears on both sides does not matter. The semantics of the assignment statement ensures that there is no confusion as to the result. The visualizer makes this very clear.
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 name 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 something to it is called an increment; subtracting is called a decrement. Sometimes programmers talk about incrementing or decrementing without specifying by how much; when they do that, they usually mean by 1. Sometimes programmers also talk about bumping a variable, which means the same as incrementing it by 1.
Incrementing and decrementing are such common operations that programming languages often include special syntax for it. In Python += is used for incrementing, and -= for decrementing. In some other languages, there is even a special syntax ++ and -- for incrementing or decrementing by 1. Python does not have such a special syntax. To increment x by 1 in Python you have to write x += 1 or x = x + 1.
After the initial statement, where we assign s to 1, we can add the current value of s and the next number that we want to add (2 all the way up to 10) and then finally reassign that that value to s so that the variable is updated after each line in the code.
The following turtle example shows some variables used for drawing, but between each use, one of the variables has its value change, resulting in a pattern. Can you predict what the turtle’s drawing will look like before you run the code?
x is updated to be the old value of x plus the value of y.
y += x
y is updated to be the old value of y plus the value of x.
x += x + y
This updates x to be its old value (because of the +=) plus its old value again (because of the x on the right side) plus the value of y, so it’s equivalent to x = x + x + y
x += y
x is updated to be the old value of x plus the value of y.
x++ y
++ is not a syntax that means anything in Python.
You have attempted 1 of 11 activities on this page.