Concepts / Updating Variables with New Values

Updating Variables with New Values

A variable is a name that refers to a value, allowing you to store and manipulate data in your program.

  • Programming
Interactive lab

Try it: Assignment, Statement by Statement

How an assignment statement evaluates its right side first (using the names' current values) and only then binds the name on the left: updating x = x + 1, augmented operators like += and //=, chained a = b = 0, simultaneous a, b = b, a + b versus one-at-a-time assignment, rebinding a name to a value of another type, the NameError for a name that was never assigned, and the SyntaxError for a name that breaks the naming rules.

How it works

  1. Before anything runs, Python compiles the whole program; a name that breaks the rules (starts with a digit, contains a space or a dash, or is a keyword) is a SyntaxError and no line runs at all.
  2. For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
  3. Then bind the name(s) on the left to that value: a new name is added to the table, an existing one is replaced (even by a value of a different type).
  4. x += 5 reads x, applies the operator (+, -, *, //, %, **) and binds the result back to x; a = b = 0 evaluates 0 once and binds a, then b.
  5. a, b = b, a + b builds the whole right-hand tuple from the OLD values before binding a and b; two separate statements would use the new a in the second line.
  6. Reading a name that is not in the table raises NameError and the program stops at that line.

Default run (10 steps): A 4-line program. Python first compiles all of it, then runs it top to bottom. The variable table on the right starts empty. … Program finished. Final table: x = 16.

Simplified: The programs are fixed templates: you choose the template, its numbers, the operator and the variable name, never the code. The lab's own small Python tokenizer and parser (written for the statements these programs use: assignments, print calls, if / elif / else, for, while, def and return) checks the text; nothing is executed as real Python. Every program the lab can show was compiled by CPython 3.12 and the lab reproduces its exception type, message, line, caret columns and the printed report. A small interpreter written for the same statements then runs them (integers of any size, the str/float results these templates produce, and print); each program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables after every line, the output and the error.

Educational simulation

Loading the simulation…

A Name Connected to a Value

A variable is a name that refers to a value. This name-value relationship lets a program store and manipulate data. When you work with a variable, you use its name to refer to the value currently connected to it.

scorevariable name10valuerefers to
Which name is bound to which value?

Creating the First Binding

An assignment statement creates a new variable and binds it to a value. Its general form is variable_name = value. For example, consider the generated assignment statement points = 5. If points did not already exist, executing this statement creates the name points and binds it to the value 5.

points = 5assignment statement5evaluated valuepointsname bound to 5evaluatesbinds under name
How does executing an assignment create a new binding that did not previously exist?
Worked example

Creating a Variable

What happens when the assignment statement points = 5 executes and points has not been used before?

  1. 1
    Evaluate the right side

    The right side produces the value 5.

  2. 2
    Use the left-side name

    The name points is used for the new variable.

  3. 3
    Create the binding

    The variable points is bound to the value 5.

Result

The program now has a variable named points that refers to 5.

Right Side First

The equals sign in an assignment statement means assign or bind; it does not mean equals in the sense of comparing two sides. Data flows from right to left. Python first evaluates the expression on the right side, producing a value. It then creates a variable with the name on the left, or updates that variable if the name already exists.

Right sideevaluate the valueProduced valueevaluation resultLeft-side namecreate or update bindingproducesbinds to
Which part of an assignment happens first, and how does the result become available through the name?

Following Several Assignments

To trace a sequence of assignments, update the name-value state after each statement. In this generated sequence, the first statement creates points, the second creates level, and the third changes points. The final state must reflect all three statements in their execution order.

No bindingsbefore executionpoints: 5after points = 5points: 5; level: 1after level = 1points: 8; level: 1after points = 8points = 5level = 1points = 8
What does the program's name-to-value state look like after each assignment executes?
Worked example

Tracing Three Statements

Trace the generated statements points = 5, level = 1, and points = 8 in order.

  1. 1
    After points = 5

    The right side produces 5, and the name points is bound to that value.

  2. 2
    After level = 1

    The right side produces 1, and a new name level is bound to that value. The existing points binding remains present.

  3. 3
    After points = 8

    The right side produces 8, and the existing name points is updated so that it refers to 8.

Result

The final state has points bound to 8 and level bound to 1.

Replacing an Existing Value

Assignment is used both to create a new variable and to update an existing one. If the left-side name already exists, Python evaluates the new right-side value and binds the existing name to that value. The name remains the same, while the value associated with it changes.

scorenamescoresame name10value15new valuerefers torefers to
What changes when a new assignment replaces a variable's old value, and what stays the same?
Best practice

When a variable is updated, write down the new state rather than combining the old and new values. For example, after score = 15 executes, the current binding is score to 15.

Mistakes in State Tracing

  • Common mistake

    Treating the equals sign as a comparison between two already-known values.

    What it looks like

    Reading points = 5 as if it asks whether points and 5 are equal.

    Why it fails

    In an assignment statement, the equals sign means assign or bind.

    Do this instead

    Read the statement as: evaluate the right side, then bind the result to the name on the left.

  • Common mistake

    Evaluating the left side first.

    What it looks like

    Starting with points when tracing points = 5.

    Why it fails

    Python evaluates the right side first.

    Do this instead

    Find the value produced by the right side before recording the left-side name.

  • Common mistake

    Keeping the old value as the current value after an update.

    What it looks like

    Saying score is still 10 after score = 15 executes.

    Why it fails

    Assignment updates an existing variable when the name already exists.

    Do this instead

    Record score as referring to 15 after the second assignment.

  • Common mistake

    Forgetting that a new left-side name creates a new variable.

    What it looks like

    Ignoring level after level = 1 executes.

    Why it fails

    An assignment statement creates a new variable when that name did not already exist.

    Do this instead

    Add the new name-value binding to the current state.

Practice the Execution Order

EASY

Trace this generated sequence in order: total = 12, category = 3, total = 20. Write the name-value state after each assignment. Then identify which name was created by the second statement and which existing name was updated by the third statement.

Hints
  • For each statement, evaluate the right side first.
  • Add a name when it appears for the first time.
  • When total appears again, update its associated value.

What do you think happens?

After the generated statements total = 12, category = 3, and total = 20 execute in order, what value does total refer to?

  • 3

  • 12

  • 20

Reveal answer
Answer:

20

The first statement binds total to 12. The second creates category and does not change total. The third assignment updates total so it refers to 20.

Key Takeaways

  1. 1
    A variable is a name that refers to a value.
  2. 2
    The assignment form is variable_name = value.
  3. 3
    The right side is evaluated first, and its result is bound to the name on the left.
  4. 4
    An assignment creates a new variable when the name is new.
  5. 5
    An assignment updates the value associated with an existing name.

At a glance

  • A variable represents a name-value relationship.
  • Assignment sends the result of the right side to the name on the left.
  • Python evaluates the right side before creating or updating the variable.
  • A new name creates a binding; an existing name receives the new value.
  • Tracing each assignment in order reveals the program's current state.

Related concepts

More concepts starting with U