Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

7.2: Updating variables

( \newcommand{\kernel}{\mathrm{null}\,}\)

A common kind of reassignment is an update, where the new value of the variable depends on the old.

>>> x = x + 1

This means “get the current value of x, add one, 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:

>>> x = x + 1
NameError: name 'x' is not defined

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

>>> x = 0
>>> x = x + 1

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.


This page titled 7.2: Updating variables is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.

Support Center

How can we help?