Skip to main content

Section 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.

Activity 6.1.1.

Activity 6.1.2.

Activity 6.1.3.

Consider the code block below. What happens when you run this program?
y = 1
x = x + 1
print(x)
  • The integer "2" prints.
  • Incorrect! Take another look at the second line. Try again!
  • We get a TypeError.
  • Incorrect! This will not cause a TypeError because x, y, and 1 are all integers. Try again!
  • We get a NameError.
  • Correct! This will cause a NameError because x has not been initialized yet.
  • The program compiles with no errors but nothing prints.
  • Incorrect! This program will not compile. Try again!
You have attempted of activities on this page.