Table of Contents
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:
- In
forloops that go through a sequence of numbers - In
whileloops where you manually increase a number each time
They are especially useful when you want to:
- Repeat something a specific number of times
- Number items (1st, 2nd, 3rd, …)
- Count how many times something happens
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 loopcounteris the loop counter variablestartis the first number (included)stopis the last number (not included)
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: 4Here:
- The loop runs 5 times
- The counter
itakes the values0, 1, 2, 3, 4
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:
- Number printed lines
- Do calculations that depend on the step number
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)stepis how much the counter changes each loop
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 # updateIf 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 + 1Counting 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 + 1Example: 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:
positive_countis a counter variable- It starts at 0
- It increases by 1 every time we find a positive number
Shorthand for Increasing Counters
The line:
positive_count = positive_count + 1is very common. Python has a shorter form:
positive_count += 1Similarly:
counter -= 1meanscounter = counter - 1counter = 2meanscounter = counter 2
These are often used when updating loop counters.
Index Counters vs Item Values
When looping through a list, there are two common patterns:
- Loop over items directly (no explicit counter)
- 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])iis a loop counter for the positionslen(names)gives the number of items in the list
This pattern is useful when you need both:
- The position (index)
- The actual value
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:
indexis the loop counter (0, 1, 2, …)nameis the value at that position
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:
- Looping 4 times when you meant 5
- Stopping at 9 when you meant 10
This is called an off-by-one error.
Common patterns to remember:
range(n)→ goes from0ton - 1(runsntimes)range(1, n + 1)→ goes from1ton(also runsntimes)
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.
continueskips to the next loop iterationbreakstops the loop completely
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:
breakOutput:
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:
iis a loop counter for the number of questionsyes_countis a counter for how many times the condition is met
Summary
- A loop counter is a variable that tracks loop progress or counts events.
- In
forloops, the counter often comes fromrange()orenumerate(). - In
whileloops, you must initialize and update the counter yourself. - Counters can track:
- How many times the loop has run
- Positions (indexes) in a collection
- How many times a condition was true
- Be careful of off-by-one errors when choosing
range()arguments. - Use
+= 1and-= 1to update counters concisely.