Skip to content

Variables and assignment

Trace a sequence of assignments in a table of names and values, including reassignment, augmented assignment and a swap of two names.

It opens on

Lines 1 and 2 start x at 4 and y at 9. After the three lines that change them, will x and y be unchanged, both 13, or swapped?

Why it matters

Every program keeps its data in named values that later lines read and change, and most beginners' bugs are a name holding a different value from the one they think it holds, so tracing names and values line by line is the core debugging skill.

Good to know first

  • Values, types and expressions: an expression such as x + y has one value, worked out from its operators in their order, and + - * // work on ints

Step by step

  1. A name bound to a value

    Trace a program of assignments line by line in a table of names and values, working out each right side before the name is bound.

    Line 1 binds x to 4, and line 2 binds y to 9; before line 2 runs, the name y has no value at all.

    A common mix-up

    x = x + y cannot work, since no number equals itself plus 9.

    In fact: It is an assignment, so the right side is worked out with the old x and then x is bound to the result.

  2. Updating a name from itself

    Rewrite an update as an augmented assignment such as += or *=, and trace a program of them.

    The line x += y means exactly x = x + y, so Python reads the old x, adds y, and binds x to the sum. With x at 4 and y at 9, it makes x 13, as before.

    A common mix-up

    Each update starts again from the first value, so n -= 4 gives 6.

    In fact: Each line reads the current value of n, which is 30 by then, so the result is 26.

  3. Swapping two names

    Swap the values of two names with a temporary name, and show why copying one name into the other loses a value.

    Lines 1 and 2 bind x to 4 and y to 9. A name holds one value at a time, so a line that binds a name to a new value drops the old one.

    A common mix-up

    x = y ties the two names together, so changing y later changes x too.

    In fact: It copies the value once; after x = y and then y = 20, x is still 9.

Try it

With a = 6 and b = 2, then a = a * b and b = a - b, what does print(a, b) show?Answer

12 10

Hint: a becomes 12 first, then b is 12 - 2

With n = 7, then n += 5, n *= 2 and n -= 3, what is n?Answer

21

Hint: n goes 12, 24, 21

With x = 5 and y = 8, what do x and y hold after t = y, y = x and x = t?Answer

x is 8 and y is 5

Hint: t saves y's 8 before y changes

Suppose x is 4. What is x after the line x = x * 3?Answer

12, because the right side 4 * 3 is worked out first, and then x is bound to 12.

The next line is n -= 4. What is n after it?Answer

26, since the line reads the n from the line before, which is 30, and 30 - 4 is 26.

Variables and assignment

30 minutes every month. No card.