Concepts / Understanding while Loops: Looping Until a Condition Changes

Understanding while Loops: Looping Until a Condition Changes

A for loop is a definite loop that processes each item in a known collection exactly once.

  • 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…

Start with a Known Collection

When a program must process every item in a collection, a for loop provides a definite pattern: it processes each item in the known collection exactly once. The collection supplies the items, and the iteration variable refers to the current item during each pass through the loop.

python
Output
red
blue
green

Trace Each Iteration

The loop above has three iterations because the collection has three items. On the first iteration, color holds red. On the second, it holds blue. On the third, it holds green. The iteration variable changes automatically as the loop moves from one collection item to the next.

colors[red, blue, green]Iteration 1color = redIteration 2color = blueIteration 3color = greenredprintedblueprintedgreenprintedfirst itemprintnext itemprintnext itemprint
What happens at each iteration as the for loop processes the known collection?

What do you think happens?

What will this loop print, and in what order?

numbers = [2, 4, 6]
for number in numbers:
    print(number)
  • 2, then 4, then 6

  • 6, then 4, then 2

  • Only 2

Reveal answer
Answer:

2, then 4, then 6

The loop processes each item in the known collection once. The iteration variable number refers to 2 during the first iteration, 4 during the second, and 6 during the third.

Read the Loop Syntax

A for loop requires the keywords for and in. The name between them is the iteration variable. The collection appears after in. A colon follows the for statement, and proper indentation identifies the statements that belong to the loop.

forloop keywordcoloriteration variableincollection keywordcolorsknown collection:statement endingintroducesprecedesselects fromfollowed by
Which part names the iteration variable, and which part supplies the collection?
Best practice

When reading a for loop, identify the iteration variable first, then identify the collection after in. Next, inspect the indented statements to determine what happens for each current item.

Follow the Iteration Variable

The iteration variable is not a separate counter that you update manually in this pattern. It holds the current collection item and changes automatically with each iteration. To trace a loop, write down the value it receives at each step and then apply the indented loop body to that value.

Worked example

Tracing Item Names

Predict the output of this loop:

animals = ["cat", "dog"]
for animal in animals:
    print("Animal:", animal)
  1. 1
    First iteration

    The iteration variable animal holds cat. The loop body prints Animal: cat.

  2. 2
    Second iteration

    The iteration variable animal changes automatically and holds dog. The loop body prints Animal: dog.

  3. 3
    End of collection

    Both known collection items have been processed once, so this loop has completed its definite sequence.

Result

Animal: catAnimal: dog

Position 1catPosition 2doganimalcatanimaldogAnimal: catoutputAnimal: dogoutputcurrent itemloop bodycurrent itemloop body
How does the iteration variable change, and which collection item does it refer to at each step?

Choose For or While

Loop typeBest fitIteration count
forProcessing each item in a known collectionKnown from the collection
whileContinuing when the number of iterations is unknownNot known in advance

The key distinction is whether the iteration count is known before the loop begins.

Use a for loop when the program has a known collection to process and the loop should visit each item exactly once. Use a while loop when the number of iterations is unknown. The supplied concept distinguishes these loops by when the iteration count is known, rather than by the name of the iteration variable.

for loopknown collectionwhile loopunknown iteration counteach item oncedefinite sequenceunknown countcondition-based choiceprocessessupports
How does control flow differ when the number of iterations is known versus unknown?

Mistakes Beginners Make

  • Common mistake

    Leaving out the for or in keyword.

    What it looks like
    color colors:
        print(color)
    Why it fails

    The required for-loop syntax includes both for and in.

    Do this instead
    for color in colors:
        print(color)
  • Common mistake

    Leaving out the colon after the for statement.

    What it looks like
    for color in colors
        print(color)
    Why it fails

    The syntax requires a colon after the for statement.

    Do this instead
    for color in colors:
        print(color)
  • Common mistake

    Failing to indent the loop body.

    What it looks like
    for color in colors:
    print(color)
    Why it fails

    Proper indentation is part of the required loop syntax and identifies the statements belonging to the loop.

    Do this instead
    for color in colors:
        print(color)
  • Common mistake

    Assuming the iteration variable keeps one value for every pass.

    What it looks like
    for color in colors:
        print(color)
    Why it fails

    The iteration variable holds the current item and changes automatically with each iteration.

    Do this instead

    Trace the current value separately for each collection item.

Practice the Trace

EASY

Trace this loop before reading the output. Record the value of item during each iteration, then write the resulting output.

items = ["pen", "book", "lamp"]
for item in items:
    print("Found", item)
Hints
  • The collection contains three items.
  • The iteration variable item receives one current collection item at a time.
  • Apply the indented print statement once for each item.
Output
Found pen
Found book
Found lamp
  1. 1
    To solve a tracing problem, count the known collection items, follow the iteration variable from the first item to the last, and apply the loop body once for each current value.

Key Takeaways

  • A for loop is a definite loop that processes every item in a known collection exactly once.
  • The iteration variable holds the current item and changes automatically with each iteration.
  • A valid for statement uses for and in, ends with a colon, and has a properly indented loop body.
  • Trace a for loop by recording the iteration variable's value at each step and applying the loop body.
  • Use for when the collection and iteration count are known; while is better when the iteration count is unknown.

Related concepts

More concepts starting with U