Concepts / Loop Structures: For and While Loops

Loop Structures: For and While Loops

Iteration is the repeated execution of statements in a loop or recursive function, and understanding loop terminology is essential for writing correct loops.

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

Why State Matters

Iteration means executing statements repeatedly in a loop or recursive function. Repetition becomes understandable when you track the state of the variables that control the loop. Before a loop begins, variables need starting values. During each iteration, those variables may be increased, decreased, or combined with new values. The loop can continue correctly only when these changes match the condition that controls repetition.

Tracing Variable State

Worked example

A counter and an accumulator

Trace a loop with a counter that begins at 0 and increases by 1 on each iteration, together with an accumulator that begins at 0 and adds the values 4, 7, and 2 in successive iterations.

  1. 1
    Initialization

    The counter starts at 0, and the accumulator starts at 0. Initialization assigns starting values before the loop begins.

  2. 2
    First iteration

    The accumulator adds 4 and becomes 4. The counter increases by 1 and becomes 1.

  3. 3
    Second iteration

    The accumulator adds 7 to its running total and becomes 11. The counter increases by 1 and becomes 2.

  4. 4
    Third iteration

    The accumulator adds 2 and becomes 13. The counter increases by 1 and becomes 3.

Result

After three iterations, the counter is 3 and the accumulator is 13. The counter records how many iterations occurred, while the accumulator records the running total of the values added.

Point in the loopCounterAccumulatorChange made
Before iteration 100Starting values
After iteration 114Counter increases by 1; accumulator adds 4
After iteration 2211Counter increases by 1; accumulator adds 7
After iteration 3313Counter increases by 1; accumulator adds 2

A state trace separates the variable that counts iterations from the variable that builds a running total.

Startcounter 0; total 0Iteration 1counter 1; total 4Iteration 2counter 2; total 11Iteration 3counter 3; total 13add 4; incrementadd 7; incrementadd 2; increment
How do the loop variables and running total change from initialization through each iteration?

Control Variables

Initialization assigns a starting value to a variable before the loop begins. Counters commonly start at 0, and many accumulators also start at 0. The choice of starting value matters because every later state depends on it.

A counter tracks how many times an event occurs. It changes by a fixed amount on each iteration, commonly by 1. An accumulator has a different purpose: it builds a running total by adding values that may vary from one iteration to the next. Both variables may begin at 0, but their roles are different.

An increment increases a variable by a fixed amount, usually 1. A decrement decreases a variable by a fixed amount. In a loop, these operations update the state that will be used during a later condition check or iteration.

TermRoleTypical changeQuestion it answers
InitializationSets a starting value before the loopAssigns the initial stateWhere does the variable begin?
CounterTracks how many times an event occursIncreases by 1 or another fixed amountHow many iterations or events have occurred?
AccumulatorBuilds a running totalAdds varying valuesWhat total has been built so far?
IncrementRaises a variableAdds a fixed amountHow does the variable move upward?
DecrementLowers a variableSubtracts a fixed amountHow does the variable move downward?

These terms describe different jobs performed by variables and variable updates in loops.

Counterfixed increaseEvent countnumber of occurrencesAccumulatorvarying additionsRunning totalcombined valuestracksbuilds
What is the difference between a variable that counts events and one that combines values?

For and While Control Flow

Both for and while loops repeat statements, so both require a clear view of the loop's state. A for-style loop is commonly traced through initialization, condition checking, the loop body, and an update before the next check. A while-style loop is commonly traced by checking the condition, executing the body when the condition permits it, and ensuring that the body or its control process changes the relevant state. In either structure, initialization comes before repetition, and updates determine what the next iteration will see.

Initializationstarting stateConditioncontinue?Loop bodyrepeated statementsUpdateincrement or decrementStopcondition no longer permitsrepetitionsetup completecontinuestopbody completenext check
How does control move through setup, condition checking, the body, and updating in a loop?

Avoiding Endless Repetition

An infinite loop occurs when repetition does not reach a stopping condition. A common cause is a control variable that is never updated. Another cause is an update that moves the variable in the wrong direction or by an amount that prevents the condition from becoming false. To avoid endless repetition, identify the variable involved in the condition and trace its value after every iteration.

Control variableinitial valueUpdated valuemoves toward stopping stateStopcondition no longer permitsrepetitionSame valueno effective updateRepeatcondition remains permittedeffective updateeventually reaches stopmissing or ineffective updatecondition stays permitted
What happens to the loop condition and control variable on each pass, and why does the loop eventually stop or continue forever?
  • Common mistake

    Using a control variable without initializing it

    What it looks like

    The loop begins by checking or updating a variable that has not been assigned a starting value.

    Why it fails

    The loop has no clearly defined initial state, making its behavior unreliable and difficult to trace.

    Do this instead

    Assign the starting value before the loop begins.

  • Common mistake

    Forgetting to update the control variable

    What it looks like

    The condition depends on a counter, but the counter remains unchanged after each pass.

    Why it fails

    The condition may remain true indefinitely, producing an infinite loop.

    Do this instead

    Add an effective increment or decrement that moves the control variable toward the stopping condition.

  • Common mistake

    Confusing a counter with an accumulator

    What it looks like

    A variable intended to count iterations is treated as though it should add changing values.

    Why it fails

    The variable no longer represents the number of events or iterations.

    Do this instead

    Use a fixed update for a counter and varying additions for an accumulator.

  • Common mistake

    Updating in the wrong direction

    What it looks like

    A control variable is decremented even though the stopping condition requires it to increase toward a boundary.

    Why it fails

    The variable can move away from the state that would end repetition.

    Do this instead

    Trace the variable after each iteration and choose an increment or decrement that progresses toward the stopping condition.

Best practice

For every loop, write down the control variable, its initial value, its update, and the condition that determines continuation. If you cannot explain how the update changes the next condition check, the loop is not yet easy to verify.

Practice the Trace

EASY

Create a state trace for a loop whose counter starts at 0 and increases by 1 on each iteration. Track the counter after four iterations. Then create a second trace for an accumulator that starts at 0 and adds 3, 5, 1, and 6 during those iterations. Identify which variable is the counter, which is the accumulator, and what each variable represents after the fourth iteration.

Hints
  • Write the initialization row before the first iteration.
  • Increase the counter by the same fixed amount each time.
  • Add the next input value to the accumulator at each iteration.
  • The counter should describe how many iterations occurred; the accumulator should describe the running total.
MEDIUM

A loop condition depends on a variable that starts at 5. The variable is never changed in the loop body. Explain why this may create an infinite loop, and describe the kind of update that would be needed to make progress toward a stopping condition.

Hints
  • Compare the variable's value before and after one iteration.
  • Ask whether the condition can become false if the value never changes.
  • An increment or decrement should move the variable toward the state required for stopping.

Key Takeaways

  1. 1
    Iteration is the repeated execution of statements in a loop or recursive function.
  2. 2
    Initialization assigns starting values before repetition begins.
  3. 3
    A counter tracks occurrences through fixed updates, while an accumulator builds a running total from varying values.
  4. 4
    Incrementing increases a variable and decrementing decreases it; these updates affect the next loop condition check.
  5. 5
    An infinite loop can result when the control variable is uninitialized, unchanged, or updated in a direction that does not lead toward stopping.

At a glance

  • Trace a loop from initialization through condition checking, the repeated body, and variable updates.
  • Use counters to record how many events occur and accumulators to build running totals.
  • Use increments and decrements deliberately because they determine the next state of the loop.
  • Prevent infinite loops by ensuring that the control variable is initialized and updated toward a stopping condition.

Related concepts

More concepts starting with L