5.1: Updating Variables

Python for Everybody · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    5.1: Updating Variables

    A common pattern in assignment statements is an assignment statement that updates 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:

    >>> 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 5.1: Updating Variables was last modified on Tue, 01 Dec 2020 03:50:51 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.