Concepts / Loop Variable Initialization and Update

Loop Variable Initialization and Update

A while loop evaluates a boolean expression before each execution of its body.

  • Programming

A Loop That Ends With a Surprising Value

A while loop repeats a block of commands as long as a condition holds. Before you can predict what a loop does, you need to know what its loop variable is doing on each pass. The loop variable is the value the condition checks and the body changes. Tracing that variable is the most reliable way to understand a while loop, and this article follows it step by step.

What do you think happens?

In the source example, a loop prints the values 1 through 5 and its variable is increased after each printed value. What is the value of the loop variable when the loop finishes?

  • 5

  • 6

  • 1

  • The loop never finishes

Reveal answer
Answer:

6

The loop prints 1 through 5, and number is updated after printing 5, so number becomes 6. The loop ends only when the next condition check finds that number is 6, which is not less than or equal to 5.

Tracing the Loop Variable Across Passes

A useful while-loop trace follows the loop variable through three jobs. First, the variable receives an initial value before the loop starts. Next, the condition uses that value to decide whether the body should run. Finally, the body changes the variable before control returns to the condition. In the source example, the variable is called number, it starts at 1, and it is increased by 1 at the end of every iteration.

number = 1initialized before the loopPass 1: check 1 <= 5True, body runsPass 1: print 1update makes number 2Pass 2: number is 2check 2 <= 5 is TruePass 5: print 5update makes number 6Check: 6 <= 5False, loop exitsnumber = 6value after the loopfirst checkrun bodyback to checkpasses continueback to checkexit
What is the value of the loop variable at the start of each pass, and how does the update change it from one pass to the next?
Worked example

Tracing number through the first two passes

number starts at 1. The loop runs while number is less than or equal to 5, prints number, then adds 1 to number. What happens on the first two passes?

  1. 1
    Initialize

    Before the loop starts, number is set to 1.

  2. 2
    Pass 1 condition

    The condition checks 1 less than or equal to 5. It is true, so the body runs.

  3. 3
    Pass 1 body

    The body prints 1. Then number is updated to 1 + 1, which is 2.

  4. 4
    Pass 2 condition

    Control returns to the condition, which now checks 2 less than or equal to 5. It is true, so the body runs again.

  5. 5
    Pass 2 body

    The body prints 2. Then number is updated to 2 + 1, which is 3.

Result

After two passes the body has printed 1 and 2, and number holds 3, ready for the next condition check.

How the Condition Decides Each Pass

Definition

A while loop evaluates a boolean expression before each execution of its body. A true condition runs the body. A false condition skips the body and continues with the next command after the loop.

number = 1initializationnumber <= 5boolean testprint numberloop bodynumber = number + 1updateNext statementafter the loopTruereturn to checkFalse
After the condition is checked, which path does execution take, and when does it return to the check?
Key point

Control never moves from the body straight to the next statement after the loop. After every pass through the body, control returns to the condition, which is checked again before the body can run another time.

Where Each Part Sits in the Code

The three jobs of the loop variable appear in three different places in the code. Initialization comes before the loop, the boolean test sits in the while line, and the update sits inside the body. The example below is an illustrative Python version of the source's count-to-five pattern, with the update placed at the end of the body.

Code walkthrough
number = 1
while number <= 5:
    print(number)
    number = number + 1
print("Final value:", number)
  1. 1
    Line 1 sets number to 1 before anything repeats.
  2. 2
    Line 2 checks whether number is less than or equal to 5 before each pass.
  3. 3
    Line 3 prints the current value of number while the test is true.
  4. 4
    Line 4 increases number by 1 at the end of the body, so the next check sees the new value.
  5. 5
    Line 5 runs after the test becomes false and shows that number is now 6.
  • number = 1 is the initialization, which runs once before the loop starts.
  • number <= 5 is the boolean test, checked before every pass.
  • print(number) is the body work, which uses the current value.
  • number = number + 1 is the update, which changes the variable before control returns to the test.
  • The final print runs after the loop exits and shows the value stored in number.
Output
1
2
3
4
5
Final value: 6

Why the Final Value Is Not the Last Printed Value

The most common error with while loops is assuming that the last value the body used is also the value the loop variable holds when the loop finishes. The source example shows why this is wrong.

  • Common mistake

    Assuming the final variable value equals the last printed value

    What it looks like

    The loop prints 1 through 5, so a learner concludes that number is 5 when the loop ends.

    Why it fails

    number is updated after printing 5, so it becomes 6. The loop only ends when the next condition check finds that number is 6.

    Do this instead

    Trace the update step after the body. The final value is the one left after the last update and the failing check.

  • Common mistake

    Placing the update before the body without accounting for the change

    What it looks like

    If the update runs first, the body prints a different value than the one the learner expects.

    Why it fails

    Moving the update changes which value the body uses on each pass, so the printed values and the final value shift together.

    Do this instead

    Read the body in order from top to bottom and apply each line in sequence when tracing.

  • Common mistake

    Forgetting that the condition is checked again before every pass, not only once at the start

When the Update Never Makes the Condition False

The loop stops only when a condition check finds the expression false. If the body never changes the loop variable in a way that makes the condition false, the check always finds it true and the body keeps running. This is an infinite loop. The example below is a generated illustration with the update removed.

python
Output (expected)
1
1
1
1
... continues on every pass until the program is stopped by hand

Practice Tracing a Loop

MEDIUM

Trace this loop without running it. Write down the value of total after each pass and state the final value of total when the loop stops. The loop is: total = 0, then while total is less than 3, add 1 to total and print total.

Hints
  • Write the value of total before the first condition check.
  • After each pass, apply the update first, then check the condition again.
  • The final value is the one left after the update that makes the condition false.

Key Takeaways

  • A while loop checks its boolean expression before each execution of the body. A true result runs the body, and a false result skips the body and continues with the next command.
  • The loop variable is initialized before the loop, used by the condition, and updated inside the body before control returns to the check.
  • The final value of the loop variable can differ from the last value the body used, because the update runs after the body and before the failing check.
  • If the update never makes the condition false, the loop becomes an infinite loop that keeps running the body.