6.1. Updating variables

Commonly, assignment statements are used to update a variable, where the new value of the variable depends on the old.

x = x + 1

This means “get the current value of x, add 1, and then update x with the new value.”

If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it assigns a value to x:

Before you can update a variable, you have to initialize it, usually with a simple assignment:

When you update a variable by adding 1 it’s called an increment; subtracting 1 is called a decrement.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

You have attempted 1 of 6 activities on this page