Kahibaro
Discord Login Register

Loop counters

What Is a Loop Counter?

A loop counter is a variable that keeps track of how many times a loop has run, or which step you are currently on.

You will most often see loop counters:

They are especially useful when you want to:

Loop Counters with `for` Loops

In Python, for loops often use a loop counter variable together with range().

Basic pattern:

for counter in range(start, stop):
    # use counter inside the loop

Example: repeat something 5 times

for i in range(5):
    print("Loop number:", i)

Output:

Loop number: 0
Loop number: 1
Loop number: 2
Loop number: 3
Loop number: 4

Here:

Starting the Counter at 1

Humans usually count from 1, but range(5) starts at 0.
To start at 1, give both start and stop values:

for i in range(1, 6):  # 1, 2, 3, 4, 5
    print("Item number:", i)

Now i goes from 1 to 5.

Using the Counter Inside the Loop

You can use the counter to:

Example: square of each number

for n in range(1, 6):
    square = n * n
    print(n, "squared is", square)

Step Size and Loop Counters

range() can also take a step value:

range(start, stop, step)

Example: counting by 2 (even numbers):

for i in range(0, 11, 2):  # 0, 2, 4, 6, 8, 10
    print(i)

Example: counting backwards:

for i in range(5, 0, -1):  # 5, 4, 3, 2, 1
    print(i)

The loop counter follows the pattern you set with start, stop, and step.

Loop Counters with `while` Loops

In a while loop, you usually create and update the loop counter yourself.

Basic pattern:

counter = start_value          # 1. initialize
while some_condition:          # 2. condition uses counter
    # do something
    counter = counter + 1      # 3. update counter

Example: repeat 5 times with a while loop

i = 0              # start
while i < 5:       # condition
    print("i is", i)
    i = i + 1      # update

If you forget to update the counter, the condition may never become false, causing an infinite loop. The counter update is what lets the loop eventually stop.

Common Counter Pattern in `while`

Counting from 1 to 5:

count = 1
while count <= 5:
    print("Count:", count)
    count = count + 1

Counting Things Inside a Loop

Sometimes the loop counter is not just “how many times we loop”, but “how many times something specific happened”.

You do this with a separate counter variable.

Basic pattern:

count = 0
for each item in something:
    if condition_is_true:
        count = count + 1

Example: count how many numbers are positive

numbers = [3, -1, 7, 0, -4, 2]
positive_count = 0
for n in numbers:
    if n > 0:
        positive_count = positive_count + 1
print("Positive numbers:", positive_count)

Here:

Shorthand for Increasing Counters

The line:

positive_count = positive_count + 1

is very common. Python has a shorter form:

positive_count += 1

Similarly:

These are often used when updating loop counters.

Index Counters vs Item Values

When looping through a list, there are two common patterns:

  1. Loop over items directly (no explicit counter)
  2. Loop over positions (indexes) using a counter

Example list:

names = ["Alice", "Bob", "Charlie"]

1. Loop over items (no manual index counter):

for name in names:
    print(name)

Here, there is no index counter; you just get each name.

2. Loop over indexes (using a counter):

for i in range(len(names)):    # i = 0, 1, 2
    print("Index:", i, "Name:", names[i])

This pattern is useful when you need both:

Using `enumerate()` for Index + Value

Python has a helper function enumerate() that gives you both index and item in one go:

for index, name in enumerate(names):
    print(index, name)

Here:

You can also start the index at 1:

for index, name in enumerate(names, start=1):
    print(index, name)

Off-by-One Errors with Counters

A very common mistake with loop counters is being off by one:

This is called an off-by-one error.

Common patterns to remember:

Example: repeat something exactly n times, starting from 1:

n = 5
for i in range(1, n + 1):  # 1, 2, 3, 4, 5
    print("Step", i)

Loop Counters with `break` and `continue`

When you use break or continue, the loop counter may not behave the way you first expect.

Skipping Some Counter Values with `continue`

for i in range(1, 6):   # 1 to 5
    if i == 3:
        continue        # skip the rest of this loop
    print(i)

Output:

1
2
4
5

The counter i still goes 1, 2, 3, 4, 5, but 3 is never printed because that iteration is skipped.

Ending the Loop Early with `break`

for i in range(1, 11):   # 1 to 10
    print("i =", i)
    if i == 4:
        break

Output:

i = 1
i = 2
i = 3
i = 4

The counter i would have gone up to 10, but break stops the loop when i reaches 4.

Practical Examples with Loop Counters

Example 1: Simple Countdown

start = 5
for i in range(start, 0, -1):
    print(i)
print("Go!")

Uses a counter that decreases each time.

Example 2: Sum of the First `n` Numbers

We want:

$$
1 + 2 + 3 + \dots + n
$$

n = 5
total = 0
for i in range(1, n + 1):
    total += i
print("Sum from 1 to", n, "is", total)

Example 3: Count How Many Times the User Enters “yes”

yes_count = 0
for i in range(3):  # ask 3 times
    answer = input("Type yes or no: ")
    if answer == "yes":
        yes_count += 1
print("You typed 'yes' this many times:", yes_count)

Here:

Summary

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!