Concepts / The for Loop: Iterating Over Sequences

The for Loop: Iterating Over Sequences

A while loop repeats code as long as a condition is true, checking the condition before each iteration.

  • Programming
Interactive lab

Try it: Loop Tracer

How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.

How it works

  1. Initialise the accumulator before the loop.
  2. Each iteration, the loop variable takes the next value from the list.
  3. An if inside the loop decides whether to update the accumulator.
  4. After the last item the loop ends and the accumulator holds the answer.

Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.

Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.

Educational simulation

Loading the simulation…

Why Repetition Needs a Loop

Suppose you need to print the numbers 5, 4, 3, 2, and 1, followed by “Blastoff!”. You could write five separate print statements. But counting down from 1000 would require an impractical number of statements. A loop lets you write a small block of code once and have Python execute it repeatedly, with slight variations each time.

The supplied material focuses on the while loop. A while loop repeatedly executes a block of code as long as a condition remains true. Python checks the condition before every possible execution of the loop body. If the condition is true, the body runs. If the condition is false, the loop stops and the program continues with the next statement.

The Countdown Execution Path

n = 5initial valuen = 5print, then decreasen = 0condition is falsen = 4print, then decreasen = 3print, then decreasen = 2print, then decreasen = 1print, then decreasen > 0decrease ndecrease ndecrease ndecrease ndecrease n; n > 0 is false
What happens as the loop checks its condition, runs its body, updates n, and repeats?
Worked example

Counting Down from Five

Determine what happens when n starts at 5, the loop continues while n > 0, and the body prints n before decreasing it.

  1. 1
    Initial check

    Python evaluates the condition with n equal to 5. Because 5 is greater than 0, the condition is true and the loop body runs.

  2. 2
    First iteration

    The body prints 5 and then decreases n to 4.

  3. 3
    Middle iterations

    The same process occurs for n equal to 4, 3, 2, and 1. Each value is printed, and n decreases by one.

  4. 4
    Final check

    After the iteration where n is 1, n becomes 0. Python checks n > 0 again. The condition is false, so the loop exits.

  5. 5
    Following statement

    After the loop exits, the program prints “Blastoff!”.

Result

The loop prints 5, 4, 3, 2, 1 and then prints “Blastoff!”.

Condition Checks and Iteration Variables

The execution flow has a fixed order. Python first evaluates the condition, which produces either True or False. If the result is False, the loop exits immediately. If the result is True, Python executes the loop body and then returns to the beginning to evaluate the condition again.

n > 0evaluate conditionLoop bodyexecute one iterationCondition againafter the bodyNext statementloop has exitedTruebody finishesrepeat checkFalse
How does the condition determine whether the loop enters another iteration or exits?
Definition

An iteration is one complete execution of the loop body. If the body executes five times, the loop has five iterations.

The iteration variable is the variable that changes inside the loop body and eventually causes the condition to become false. In the countdown, n is the iteration variable. The body decreases n so that the value moves toward the condition becoming false.

When the Loop Cannot Finish

n > 0condition remains trueprint(n)body executesnvalue does not changeCondition againsame true resultTrueno updatereturncheck again
How does control keep returning to the condition when the iteration variable never moves toward termination?

An infinite loop occurs when the condition never becomes false. One cause is that the iteration variable never changes. Another cause is that it changes in a direction that keeps the condition true. For example, with a condition such as n > 0, failing to decrease n means that n remains greater than 0, so the loop continues indefinitely.

  • Common mistake

    Leaving the iteration variable unchanged

    What it looks like

    A loop checks whether n > 0 and prints n, but never decreases n.

    Why it fails

    The condition remains true because n never moves toward zero.

    Do this instead

    Modify the iteration variable inside the body so that it moves toward making the condition false.

  • Common mistake

    Changing the variable in the wrong direction

    What it looks like

    A loop uses n > 0 but changes n so that it becomes larger rather than smaller.

    Why it fails

    The change keeps the condition true instead of moving toward termination.

    Do this instead

    Check whether the update moves the variable toward the condition becoming false.

  • Common mistake

    Assuming the body runs before the first condition check

    Why it fails

    A while loop checks its condition before every execution, including the first possible iteration.

    Do this instead

    Trace the initial condition before counting any iteration.

  • Common mistake

    Miscounting iterations

    Why it fails

    An iteration means one complete pass through the body, not one condition check that returns False.

    Do this instead

    Count only the times the loop body actually executes.

Manual Tracing for Debugging

When a loop produces unexpected output, trace it one step at a time. Before each possible iteration, write down the current value of the iteration variable and the result of the condition. Then record what the body does and what value the variable has afterward. This exposes the exact point where execution diverges from your expectation.

CheckValue of nCondition n > 0Body executes?
15TrueYes
24TrueYes
33TrueYes
42TrueYes
51TrueYes
60FalseNo

A manual trace separates condition checks from actual iterations. The sixth check does not create a sixth iteration because the body does not execute.

What do you think happens?

A countdown starts with n equal to 5 and continues while n > 0. How many iterations occur before the condition becomes false?

  • 4

  • 5

  • 6

  • The loop never terminates

Reveal answer
Answer:

5

The body executes when n is 5, 4, 3, 2, and 1. After the fifth iteration, n becomes 0. The next condition check is false, so it exits without a sixth iteration.

Practice the Trace

EASY

Create a trace for a countdown whose iteration variable starts at 3, whose condition is that the variable is greater than 0, and whose body decreases the variable by 1. Record the variable's value before each condition check, whether the body runs, and the total number of iterations.

Hints
  • List the values tested before the body runs.
  • Remember that the condition is checked once more after the final iteration.
  • Count body executions, not all condition checks.
MEDIUM

A loop is expected to run five times, but its output suggests that it runs six times. Describe the trace information you would write down to find the extra iteration.

Hints
  • Record the iteration variable before every body execution.
  • Check the value immediately after the fifth body execution.
  • Inspect the condition that permits the next pass.

Key Takeaways

  1. 1
    A while loop checks its condition before each possible iteration.
  2. 2
    A true condition runs the body; a false condition exits the loop and continues with the next statement.
  3. 3
    An iteration is one complete execution of the loop body.
  4. 4
    The iteration variable must change toward making the condition false.
  5. 5
    Manual tracing records the variable and condition at each check and helps reveal logic errors.

At a glance

  • A while loop repeats a body while its condition remains true.
  • Python checks the condition before every iteration, including the first possible one.
  • The iteration variable must move toward making the condition false, or the loop may become infinite.
  • Tracing values and condition results helps distinguish iterations from checks and exposes unexpected behavior.

Related concepts

More concepts starting with T