Concepts / Loops and Counters

Loops and Counters

Variable updates are not special operations; they follow the same evaluation rules as all assignments: Python evaluates the right side first, then stores the result in the variable on the left.

  • Programming

A Counter Needs a Starting Point

A variable update uses the variable’s current value to calculate its next value. That means Python must already be able to find the variable before the update begins. Initialization supplies this first value. Without initialization, Python cannot find the variable’s current value and raises a NameError.

Establishing the first counter value

A counter must begin at 0 and then be increased by 1.

Initialize: Store the initial value 0 in the variable count. The variable now has a current value that Python can look up.

Update: Use the current value of count to calculate its next value by adding 1.

Store: Store the calculated result back in count.

The counter changes from 0 to 1 because its first value existed before the update.

read during updateinitial value storedcountno current valueNameErrorupdate cannot read countcount0countready for update
What value does a counter contain before its first update, and what happens if Python tries to read it before initialization?

Read, Calculate, Store

An update such as count = count + 1 follows the ordinary rules of assignment. Python first evaluates everything on the right side. It looks up the current value of count, adds 1 to that value, and obtains a result. Only then does Python store that result in the variable on the left. The old value is therefore used to calculate the new value before the variable receives the replacement value.

look upadd 1store resultcount5current value55 + 16count6
What happens first when Python evaluates count = count + 1: does it read the old value, calculate the new value, or replace the variable first?

What do you think happens?

Suppose count currently has the value 5. In count = count + 1, what value is used before the new value is stored?

  • The current value 5
  • The new value 6
  • No value, because the left side is processed first
Reveal answer

Answer: The current value 5

Python evaluates the right side first. It reads 5, calculates 5 + 1, and then stores 6 in count.

Following Values Across Updates

The safest way to understand an update is to trace one change at a time. For each update, identify the current value, perform the arithmetic on the right side, and replace the variable with the result. The variable moves from one state to the next; it does not use its new value until the current update has finished.

Tracing a running total

A variable total starts at 10. Two updates add 4 and then 7.

Initial state: total has the value 10.

First update: Python reads the current value 10, calculates 10 + 4, and stores 14 in total.

Second update: Python now reads the current value 14, calculates 14 + 7, and stores 21 in total.

The successive values are 10, 14, and 21.

current valueaddstore resulttotal10price410 + 414total14
How does the current value move through an update such as total = total + price to become the next value?

Counter Progression

When the same update pattern is applied repeatedly, each result becomes the current value for the next update. This creates a progression of states. For an increment, the arithmetic adds to the current value. For a decrement, the arithmetic subtracts from the current value. Both operations require the variable to have been initialized first.

add 1add 1add 1count0iteration 1count becomes 1iteration 2count becomes 2iteration 3count becomes 3
How does a counter’s value change on each loop iteration, and how do the successive values correspond to the iterations?
OperationArithmeticDirection
IncrementAdd 1 to the current valueValue increases
DecrementSubtract 1 from the current valueValue decreases

Mistakes That Break Updates

  • Updating a variable before initializing it.

    Python cannot look up the current value needed to evaluate the right side, so it raises a NameError.

    Fix: Give the variable an initial value before applying an update.

  • Assuming the left side is replaced before the right side is evaluated.

    Python evaluates the right side first. The old value is needed for the calculation.

    Fix: Trace the operation in this order: look up the current value, perform the arithmetic, and store the result.

  • Ignoring the value produced by the previous update.

    After an update, the result becomes the variable’s current value for the next update.

    Fix: Record the variable’s value after each update before tracing the next one.

When checking an update, write a short state trace. For every step, record the value before the update, the arithmetic performed on the right side, and the value stored afterward. This makes initialization errors and incorrect value transitions easier to identify.

Check Your Trace

EASY

A variable score is initialized to 3. It is incremented once, then incremented again, and then decremented once. Write the value of score after each update and identify the value used on the right side at every step.

Hints
  • Begin with the initialized value 3.
  • For each update, use the result of the previous update as the current value.
  • An increment adds 1; a decrement subtracts 1.

Practice solution

score starts at 3, is incremented, is incremented again, and is then decremented.

First update: Read 3 and add 1. The new value is 4.

Second update: Read the current value 4 and add 1. The new value is 5.

Third update: Read the current value 5 and subtract 1. The new value is 4.

The values after the three updates are 4, 5, and 4.

Key Takeaways

  1. Initialize a variable before updating it so Python has a current value to read.
  2. Python evaluates the right side of an assignment before storing the result in the variable on the left.
  3. A variable update follows the sequence: look up the current value, perform the arithmetic, and store the result.
  4. Each update produces the current value used by the next update.
  5. An increment adds 1, while a decrement subtracts 1.

Key Takeaways

  • A variable must be initialized before an update can read its current value.
  • Python reads and evaluates the right side before replacing the variable on the left.
  • Repeated updates form a progression in which each result becomes the next current value.
  • Incrementing adds 1, while decrementing subtracts 1.