Using for Loops
A for loop repeats a block of code for each item in a sequence, assigning each item to a loop variable one at a time.
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
- Initialise the accumulator before the loop.
- Each iteration, the loop variable takes the next value from the list.
- An if inside the loop decides whether to update the accumulator.
- 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.
Loading the simulation…
One Item at a Time
Suppose a task must be performed for every item in a sequence. A for loop handles this repetition by taking one item from the sequence, assigning it to a loop variable, and repeating the loop body. After that iteration, it takes the next item and does the same thing. The central question is not how many times to repeat blindly, but which item is being processed during the current iteration.
Tracing Each Iteration
What do you think happens?
A loop processes the sequence ["red", "green", "blue"] in order. What values does the loop variable receive?
Reveal answer
red, then green, then blue
A for loop assigns each item in the sequence to the loop variable one at a time. The loop body therefore runs once with red, once with green, and once with blue.
To trace a for loop, write down the sequence in its order. Then move through the sequence one item at a time. For each item, record the value assigned to the loop variable and determine what the loop body does with that value. The complete output is the ordered combination of the results from those iterations.
The range Function
The range() function generates a sequence of numbers. Its start, stop, and step parameters let you control where the numeric sequence begins, where it ends, and how the values change between items.
| Form | Meaning | Generated values |
|---|---|---|
| range(stop) | Begins at the default starting point and advances by the default step of 1 until stop is reached | Depends on stop |
| range(start, stop) | Begins at start and advances by 1, stopping before stop | start through the value before stop |
| range(start, stop, step) | Begins at start and changes by step, stopping before the stop boundary | Values determined by start, stop, and step |
The source describes range() as having customizable start, stop, and step parameters. With start and stop, the stop value is not included; the default increment is 1.
Worked Traces
Counting by Two
Predict the values processed by a for loop that uses range(2, 10, 2).
- 1Read the parameters
The starting value is 2, the stopping boundary is 10, and the step is 2.
- 2Begin at start
The first value is 2.
- 3Apply the step
Add 2 repeatedly to obtain 4, 6, and 8.
- 4Check the boundary
The stop value 10 is not included, so the sequence ends before 10.
The loop processes 2, then 4, then 6, then 8.
for number in range(2, 10, 2):
print(number)- 1
range(2, 10, 2)generates 2, 4, 6, and 8. - 2The first iteration assigns 2 to number, so the output is 2.
- 3The next iterations assign 4, 6, and 8 to number in order.
- 4The value 10 is the stop boundary and is not processed.
- number receives one value from the numeric sequence on each iteration
- the loop body processes the current value by printing it
2
4
6
82
4
6
8Counting Backward
Determine the values generated by range(5, 0, -1).
- 1Read the parameters
The sequence starts at 5, has a stopping boundary of 0, and changes by -1.
- 2Move backward
Subtract 1 after each value: 5, 4, 3, 2, then 1.
- 3Apply the stop rule
The stop value 0 is not included.
The generated values are 5, 4, 3, 2, and 1.
Choosing the Structure
A for loop is an appropriate control structure when the task involves processing each item in a known sequence. The sequence may contain items such as names or other values, or it may be generated numerically with range(). The loop makes the item-by-item progression explicit: the loop variable represents the current item, and the loop body describes how that item is processed.
Mistakes Beginners Make
Common mistake Expecting the stop value to be included
What it looks likeAssuming range(2, 6) produces 2, 3, 4, 5, and 6Why it failsThe stop value is not included.
Do this insteadTrace the sequence as 2, 3, 4, and 5.
Common mistake Forgetting that the default step is 1
What it looks likeReading range(3, 7) as if it skipped numbersWhy it failsWith start and stop specified, the values advance by 1 by default.
Do this insteadUse a third parameter when a different increment is required.
Common mistake Ignoring the direction of the step
What it looks likeExpecting range(5, 0, -1) to count upwardWhy it failsA negative step makes the values move backward.
Do this insteadUse the sign and size of the step to trace the direction and increment.
Common mistake Treating the loop variable as the whole sequence
What it looks likeThinking the loop variable represents every item at once
Why it failsThe loop variable receives one item at a time.
Do this insteadTrace the value of the loop variable separately for each iteration.
Practice Trace
Predict the values processed by this loop before checking your answer: for value in range(10, 4, -2). List the values in the order the loop variable receives them, and identify which stop value is excluded.
Hints
- Start at 10.
- Apply a step of -2 after each value.
- Stop before reaching 4.
Practice Answer
Trace range(10, 4, -2).
- 1Start
The first value is 10.
- 2Apply the step
Subtract 2 to get 8, then 6.
- 3Check the boundary
The next value would be 4, but the stop value is excluded.
The loop variable receives 10, then 8, then 6. The excluded stop value is 4.
Key Takeaways
- A for loop repeats its body for each item in a sequence.
- The loop variable receives one sequence item at a time.
range(start, stop)begins at start, advances by 1 by default, and excludes stop.- A third
range()parameter controls the step, including backward counting with a negative step. - To predict output, list the sequence and trace the loop variable through each iteration.