Concepts / While Loops

While Loops

The condition is checked before every iteration, not only before the first one. This is why a condition that is already false prevents the loop body from running at all.

  • Programming
Interactive lab

Try it: while Loops, break and continue

How a while loop re-evaluates its condition before every pass, how break leaves the loop at once, how continue jumps back to the condition, how a sentinel value ends a while True loop, and why a loop whose condition never becomes False runs forever.

How it works

  1. Evaluate the condition. If it is False, skip the body and continue after the loop.
  2. If it is True, run the body from the top, then go back and evaluate the condition again.
  3. continue skips the rest of the body and goes straight back to the condition check.
  4. break leaves the loop immediately; the condition is not checked again (while True loops rely on it, e.g. stopping at a sentinel like 'done').
  5. If nothing in the body can make the condition False, the loop never ends; the lab's guard stops it after N iterations and says so.

Default run (21 steps): Ready: Countdown. A while loop checks its condition before every pass. … Finished after 5 iterations and 6 condition checks.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type in the list, one per call (the prompt is not printed), and raises EOFError when they run out, like a closed keyboard stream. The guard is the lab's, not Python's.

Educational simulation

Loading the simulation…

Repetition with a Condition

A while loop repeats a block of code as long as a condition is true. Instead of writing the same instructions multiple times, you write the loop body once and allow the loop to repeat it. The key question is not how many repetitions should happen in advance, but whether the condition is still true when the loop checks it.

In the real world

A number-guessing game provides a practical way to think about a while loop. The program continues the guessing activity while the needed condition remains true, and it stops when that condition is no longer true.

The Repeating Cycle

Every cycle follows the same order. Python evaluates the condition first. If the condition is true, Python enters the loop body and executes its instructions. After the body finishes, Python returns to the condition and evaluates it again. If the condition is false, Python exits the loop immediately instead of running the body.

ConditionLoop bodyState updateExittruefalsefinishescheck again
How does execution move between checking the condition, running the loop body, updating state, and repeating or exiting?
Key point

The condition is checked before every iteration, not only before the first one. This is why a condition that is already false prevents the loop body from running at all.

Tracing Repeated Checks

Worked example

A Counter Moving Toward the Stopping Point

Imagine a loop whose condition is true while a counter is below 3. The loop body changes the counter so that it moves closer to 3 on each iteration.

  1. 1
    Initial check

    The counter begins below 3, so the condition is true and the loop body runs.

  2. 2
    First iteration

    The loop body performs its action and changes the counter. Python then returns to the condition.

  3. 3
    Second check

    If the counter is still below 3, the condition remains true, so the body runs again.

  4. 4
    Final check

    After another state change, the counter reaches the stopping point. The condition becomes false, so Python exits before another body execution.

Result

The loop terminates because the value used by the condition changes until the condition becomes false.

Iteration 1condition trueCounter below 3body runsIteration 2condition trueCounter below 3body runsFinal checkcondition falseExitbody does not runenter bodycheck againenter bodycheck againleave loop
What happens to the condition, loop body, and variable values during each iteration until the loop stops?

Tracing means recording three things at each stage: the condition's result, whether the body runs, and how the value connected to the condition changes. This method makes the stopping point visible instead of treating the loop as an unexplained repetition.

Termination and Infinite Repetition

A while loop terminates when its condition becomes false. For that to happen, something in the loop body must change the condition variable or otherwise change the situation tested by the condition. If the condition variable never changes in a way that can make the condition false, the loop continues forever. This is an infinite loop.

Condition truebody can runChanged conditionvaluecondition checked againCondition falseloop exitsUnchanged conditionrepetition continuesCondition falsebody skippedbody changes stateeventually becomes falsestate does not progresscontinues checkingexit immediately
What change causes the condition to become false, and what happens when the condition is initially false or never becomes false?
Before

Condition remains true because the condition variable is not changed.

The loop keeps returning to the condition with no progress toward false.

After

Condition becomes false after the loop body changes the condition variable.

The loop eventually reaches a false condition and exits.

A Guessing Task

A number-guessing game illustrates a practical use of a while loop. The program keeps the guessing activity inside the repeated process, checks the relevant condition before each iteration, and stops when the condition is no longer true. The important design idea is that each attempt must move the game toward a condition that can end the repetition.

Guesschanging inputCondition checkcontinue or stopGuessing actionloop bodyCorrect guesstask completeprovide valuecondition remains truetry againcompletion condition
How does changing input move through repeated checks and actions until the practical task is complete?
Key point

The practical problem determines what must change inside the loop. In the guessing example, the repeated activity is useful only if the guesses and condition checks can eventually reach completion.

Mistakes Beginners Make

  • Common mistake

    Assuming the loop body runs at least once

    What it looks like

    The condition is false before the first check completes.

    Why it fails

    A while loop checks its condition before each iteration. When the first check is false, the loop exits immediately.

    Do this instead

    Trace the initial condition before tracing any body actions.

  • Common mistake

    Failing to change the condition variable

    What it looks like

    The loop body runs, but the value tested by the condition never changes.

    Why it fails

    The condition can remain true forever, creating an infinite loop.

    Do this instead

    Identify the state change that moves the condition toward false.

  • Common mistake

    Stopping the trace after one iteration

    What it looks like

    The first body execution is treated as the entire loop.

    Why it fails

    After the body finishes, Python checks the condition again and may execute another iteration.

    Do this instead

    Record every condition check until the condition becomes false.

  • Common mistake

    Ignoring normal loop exit behavior

    What it looks like

    The learner focuses only on the repeated body and not on the condition that ends it.

    Why it fails

    Understanding the exit condition is necessary for explaining why the loop terminates.

    Do this instead

    State exactly what changes and when the condition becomes false.

A Reliable Tracing Method

  1. 1
    Write down the condition that controls repetition.
  2. 2
    Record the condition's initial result before the body runs.
  3. 3
    If the result is true, record what the loop body does.
  4. 4
    Record how the condition variable or related state changes.
  5. 5
    Return to the condition and repeat the trace.
  6. 6
    Stop when the condition is false, or identify an infinite loop if the condition never becomes false.
MEDIUM

Describe the execution of a while loop used for a number-guessing task. Identify the condition, explain what happens when it is true, state what must change during the loop, and explain what happens when the condition becomes false.

Hints
  • Begin with the condition check before the first iteration.
  • Separate the repeated body from the condition that controls it.
  • Explain how the task can move toward normal termination.

Key Takeaways

  1. 1
    A while loop repeatedly executes its body while a condition is true.
  2. 2
    The condition is checked before every iteration.
  3. 3
    A false condition causes immediate exit, including when it is false initially.
  4. 4
    The loop body must change the condition variable or relevant state so the condition can become false.
  5. 5
    If the condition never becomes false, the loop is infinite.
  6. 6
    A number-guessing task is a practical example of repeating an action until a completion condition is reached.

At a glance

  • A while loop repeats code as long as its condition remains true.
  • Python checks the condition before every iteration and exits immediately when it is false.
  • A condition variable or related state must change so the loop can terminate.
  • Tracing each condition check, body execution, and state change reveals the loop's full execution flow.
  • Number-guessing is a practical task that can be organized around repeated checks until completion.

More concepts starting with W