← Back to Blog

Keeping score — the loop counter

The problem...

Your loop runs. But you have no idea what happened inside.

How many times did it run? What was the total? What changed?

You need a way to track what's happening — iteration by iteration.

The idea!

A counter is just a variable you define before the loop and update inside it. Simple. Powerful. Essential.

Counting iterations

word = "Bull"
count = 0

for letter in word:
    count += 1

print(f"Loop ran {count} times.")    # Loop ran 4 times.

count starts at 0. Every iteration adds 1. After the loop — the total is ready.

Adding up values

word = "RedHorn"
total = 0

for letter in word:
    total += 1

print(f"Total characters: {total}")    # Total characters: 7

Same pattern — different purpose. The counter accumulates whatever you need.

Subtracting with -=

fuel = 100

for stop in range(5):
    fuel -= 10
    print(f"After stop {stop + 1}: {fuel} units remaining")
# After stop 1: 90 units remaining
# After stop 2: 80 units remaining
# After stop 3: 70 units remaining
# After stop 4: 60 units remaining
# After stop 5: 50 units remaining

Every iteration consumes fuel. The variable tracks what's left.

Multiplying with *=

value = 1

for i in range(1, 6):
    value *= i
    print(f"{i}! = {value}")
# 1! = 1
# 2! = 2
# 3! = 6
# 4! = 24
# 5! = 120

Each iteration multiplies the current value by the next number. That's factorial — built with a loop and a counter.

The pattern

# 1. Define the variable before the loop
counter = 0

# 2. Update it inside the loop
for item in sequence:
    counter += 1    # or -=, *=, whatever you need

# 3. Use it after the loop
print(counter)

Always the same structure. The operation changes — the pattern doesn't.

Heads up!

  • Define the variable before the loop — not inside it
  • If you define it inside, it resets on every iteration
  • += adds, -= subtracts, *= multiplies — all update in place
  • The variable is accessible after the loop ends — use it there

The mindset shift

Stop thinking: "The loop just runs."

Start thinking: "The loop runs — and I can track everything that happens inside it."

What you should understand now

  • A counter is a variable defined before the loop and updated inside
  • += accumulates, -= depletes, *= multiplies — iteration by iteration
  • Always define the counter before the loop — never inside
  • The counter holds its value after the loop ends
[ login to bookmark ] // copied! 32 views · 2 min
// resources
Code Example loop_counter.py
← prev From here to there — range() next → Position and value — at the same time
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.