Concepts / For Loops and Loop Control

For Loops and Loop Control

The counter pattern is a fundamental computational technique: initialize a counter to 0, loop through data, check a condition, and increment the counter when the condition is true.

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

One Question, Many Matches

Suppose you need to answer a simple question: how many times does the letter a appear in banana? The answer is 3, but the useful programming idea is how to arrive at that answer. A loop can examine each character, a condition can decide whether the character matters, and a counter can remember how many matches have been found so far.

Key point

The counter pattern records a running total. It starts at 0, examines data repeatedly, and increases only when the current item satisfies a condition.

Tracing Banana Character by Character

What do you think happens?

Before reading the trace, predict the counter value after each character in banana is examined while counting the letter a.

  • 0, 1, 1, 2, 2, 3

  • 1, 1, 2, 2, 3, 3

  • 0, 0, 1, 1, 2, 2

Reveal answer
Answer:

0, 1, 1, 2, 2, 3

The counter begins at 0. It increases at the second, fourth, and sixth characters because those positions contain a.

bcount 03final countacount 1ncount 1acount 2ncount 2acount 3next characternext characternext characternext characternext characterloop ends
How does the loop move through each character in banana and connect matching characters to the final count?
PositionCharacterMatches a?Counter after checking
0bNo0
1aYes1
2nNo1
3aYes2
4nNo2
5aYes3

The counter changes only at positions containing the target character.

The important observation is not merely that the final count is 3. The counter changes selectively. It stays unchanged for b, n, and n. It increases by exactly 1 for each a. This selective update is the central behavior of the counter pattern.

The Four-Part Counter Pattern

count = 0initializeNext characteriterateletter == targetcheck conditioncount + 1matchFinal countafter all characterscountno matchbegin loopexaminetruefalsecontinuecontinueno characters remain
What happens after each character is examined, and how does the condition determine whether the counter is incremented?
  1. 1
    Initialize the counter to 0 before the loop begins.
  2. 2
    Use a for loop to examine each item in the data.
  3. 3
    Check whether the current item satisfies the condition.
  4. 4
    Increment the counter when the condition is true.
  5. 5
    Use the counter after the loop to obtain the accumulated result.

Initialization gives the counter a known starting state. Iteration supplies one character at a time. The condition separates matching characters from non-matching characters. Conditional incrementing ensures that only successful matches contribute to the result.

python
Output (expected)
3

Following the Counter State

0before b0after b1after a1after n2after a2after n3after ab: no matcha: incrementn: no matcha: incrementn: no matcha: increment
How does the counter value change on each iteration when the current character matches the target?

A useful tracing habit is to write down the counter after every iteration. For banana, the sequence is 0, 1, 1, 2, 2, 3. The repeated values are meaningful: they show that the loop examined a character that did not satisfy the condition. A counter does not need to change on every iteration.

Best practice

When debugging a counter loop, record three values for each iteration: the current character, whether the condition is true, and the counter after the condition is processed. This makes it easier to locate an incorrect increment or an incorrect comparison.

From One Loop to a Reusable Function

Stringtext to searchcountloop and conditionCountresult returnedTarget charactercharacter to countfirst argumentsecond argumentreturn
How do the string and target character enter the function, and how does the resulting count come back to the caller?

Once the loop works for one string and one target character, the same logic can be encapsulated in a function named count. The function accepts the string to search and the letter to count as two arguments. This separates the reusable counting process from the particular values supplied by a caller.

python
Output (expected)
3

The function keeps the counter local to the counting task, examines each character in the supplied string, and returns the accumulated result. Changing the arguments lets the same pattern count a different character in a different string without rewriting the loop.

Mistakes That Break the Count

  • Common mistake

    Initializing the counter inside the loop

    What it looks like

    The counter is reset to 0 each time another character is examined.

    Why it fails

    Earlier matches are erased instead of accumulated.

    Do this instead

    Initialize the counter to 0 before the loop begins.

  • Common mistake

    Forgetting to increment the counter

    What it looks like

    The condition identifies a matching character, but the counter is never increased.

    Why it fails

    The loop detects matches without recording them, so the accumulated result cannot grow.

    Do this instead

    Increment the counter inside the conditional branch that handles a true match.

  • Common mistake

    Using assignment instead of comparison

    What it looks like
    Using = where the condition should compare the current character with the target.
    Why it fails

    The condition needs to test whether two values are equal.

    Do this instead
    Use == for the character comparison described by the pattern.
  • Common mistake

    Placing the increment outside the if block

    What it looks like

    The counter is increased after every character, whether or not it matches.

    Why it fails

    Non-matching characters are counted as though they satisfied the condition.

    Do this instead

    Place the increment inside the if block so only matching characters contribute.

Before
count = 0
for letter in text:
    if letter == target:
        pass
    count = count + 1

The counter increases for every character.

After
count = 0
for letter in text:
    if letter == target:
        count = count + 1

The counter increases only for matching characters.

Practice the Pattern

MEDIUM

Write a function named count that accepts two arguments: a string to search and a target character. Use the counter pattern to count how many times the target appears. Test your function with banana and a, then trace the counter after each character.

Hints
  • Create the counter before the loop and set it to 0.
  • Use the for loop variable as the current character.
  • Compare the current character with the target using ==.
  • Increment only when the comparison is true.
  • Return the counter after all characters have been examined.
Initializecounter = 0Iterateeach characterCheckmatches target?Incrementon true conditionResultaccumulated countstartexaminematchrepeatno matchno items remain
How do initialization, repeated checking, conditional incrementing, and the final result fit together as a general pattern?

Pattern Summary

  1. 1
    The counter pattern starts by initializing a counter to 0.
  2. 2
    A for loop examines each item in the data, and an if statement checks whether it matches the target condition.
  3. 3
    The counter changes only when the condition is true; it remains unchanged when the condition is false.
  4. 4
    Counting characters in a string is a direct application of this pattern.
  5. 5
    A function with string and target-character parameters turns the counting logic into a reusable tool.

At a glance

  • The counter pattern combines initialization, iteration, conditional checking, and selective incrementing.
  • For banana, the counter increases at the three positions containing a and ends at 3.
  • Tracing the counter after every iteration reveals why it changes or stays the same.
  • Encapsulating the pattern in a count function makes it reusable for different strings and target characters.

Related concepts

More concepts starting with F