Concepts / While Loops: Repeating Code Until a Condition Changes

While Loops: Repeating Code Until a Condition Changes

An infinite loop never terminates because its condition never becomes false.

  • Programming

Why Repetition Needs Control

Imagine printing the numbers 5, 4, 3, 2, and 1, followed by “Blastoff!” Writing one print statement for each number is possible, but it becomes impractical when the countdown starts at 1000. A loop lets you write a small block of code once and have Python execute it repeatedly, with values changing between passes.

A while loop repeats its body as long as a condition is true. Python checks the condition before every iteration. A true result runs the body; a false result stops the loop and continues with the next statement after it.

truecheck againfalseConditionTrue or FalseLoop bodyOne iterationNext statementLoop ends
What happens next after the loop body runs, and how does execution return to the condition check?

Tracing a Countdown

python

Following n from 5 to 0

Determine what happens during each pass of the countdown loop.

Initial check: n starts at 5. The condition n > 0 is true, so the body runs.

First iteration: The loop prints 5 and changes n to 4.

Continuing iterations: The same pattern continues for n values 4, 3, 2, and 1. Each pass prints the current value and decreases n by 1.

Final check: After the pass for n equal to 1, n becomes 0. The condition 0 > 0 is false, so the loop body does not run again.

After the loop: Execution continues to the next statement, which prints “Blastoff!”

The loop body executes five times and prints 5, 4, 3, 2, 1. Then the program prints “Blastoff!”

Output
5
4
3
2
1
Blastoff!
decrease by 1decrease by 1decrease by 1decrease by 1decrease by 1n = 5n > 0: truen = 4n > 0: truen = 3n > 0: truen = 2n > 0: truen = 1n > 0: truen = 0n > 0: false
How does the iteration variable change on each pass, and when does it make the condition false?

The Iteration Variable

An iteration is one complete execution of the loop body. The iteration variable is the variable that changes inside the body and eventually causes the condition to become false.

In the countdown, n is both part of the condition and the value changed by the body. The condition checks whether n is greater than zero, while the body decreases n. This relationship is what moves the loop toward termination. A terminating loop has a finite starting value, a condition that checks that value, and code that moves it toward the stopping point.

checkedcheckednchanges toward 0n > 0eventually falsendoes not changen > 0stays true
What is different between a loop whose controlling variable progresses toward a limit and one whose controlling value never changes?

When Conditions Never Change

An infinite loop never terminates because its condition never becomes false. One cause is a missing iteration-variable change. For example, if n begins greater than zero and the loop only prints n without decreasing it, n remains greater than zero on every check, so the loop continues forever.

python
always truecheck againalways trueTrueconditionLoop bodyexecutesTruecondition unchanged
What prevents the condition from ever becoming false when the while condition is the constant True?
python

Predicting Termination

What do you think happens?

Will this loop terminate, and what value causes it to stop? n = 3 while n > 0: print(n) n = n - 1

  • It terminates when n becomes 0
  • It terminates when n becomes 1
  • It never terminates
Reveal answer

Answer: It terminates when n becomes 0.

The body decreases n on every iteration. The condition remains true for n values 3, 2, and 1. After the iteration for 1, n becomes 0, making n > 0 false.

inspect bodyyesnoLoop conditionfind its variablesVariable changemoves toward falseFalseloop stopsTrueloop continues
What condition must change, and what value will cause the loop to stop?
MEDIUM

For each loop, identify the iteration variable, state whether it changes, and predict whether the loop terminates. 1. n = 2 while n > 0: n = n - 1 2. n = 2 while n > 0: print(n) 3. while True: print("running")

Hints
  • Compare each condition with the value used in it.
  • Look for a body statement that changes the controlling value.
  • A constant True condition does not become false on its own.

Debugging a Runaway Loop

When a while loop produces unexpected output or keeps running, trace it step by step. Before each iteration, write down the controlling variable and the result of the condition. Then check whether the body changes that variable in a direction that can eventually make the condition false.

trueno useful changecheck againvalue moves to falseCondition checkrecord the valueLoop bodyinspect changesSame conditioncycle continuesStopping conditioncondition becomes false
Where does control keep cycling, and where can execution be stopped or a stopping condition be added?
  • Forgetting to change the iteration variable.

    The condition depends on n, but n never changes. If it starts greater than zero, every check remains true.

    Fix: Change n inside the body in a way that moves it toward the value that makes n > 0 false.

  • Assuming that running the loop body automatically ends the loop.

    Only the condition controls termination.

    Fix: Trace the condition before every iteration and identify the body statement that can make it false.

  • Using while True without identifying an exit path.

    The condition is the constant True, so it does not become false by itself.

    Fix: Determine the specific event or stopping mechanism intended to end the loop.

Before running a while loop, answer three questions: Which variable or value appears in the condition? Does the loop body change it? How does that change eventually make the condition false? If you cannot answer the third question, inspect the loop before allowing it to run.

Key Takeaways

  1. A while loop checks its condition before each iteration and runs its body only when the condition is true.
  2. A terminating loop uses a finite iteration variable whose changing value eventually makes the condition false.
  3. An infinite loop occurs when the condition never becomes false, often because the controlling value does not change or because the condition is the constant True.
  4. The body executes once per iteration, and tracing the controlling value before each check reveals why a loop stops or continues.
  5. When debugging a runaway loop, identify the condition, track its variables, and find the missing or ineffective change.

Key Takeaways

  • A while loop repeats code while its condition remains true.
  • The iteration variable must change toward a value that makes the condition false.
  • A missing variable change or a constant True condition can produce an infinite loop.
  • Tracing the condition and controlling variable one iteration at a time is a practical way to diagnose runaway loops.