Counters
In this tutorial, we'll update a value each time a loop runs.
A counter is a variable that changes by a regular amount each time a loop runs.
count = 0
while count < 5:
print(count)
count = count + 1
The line count = count + 1 is what moves the loop forward.
Counting Up
number = 1
while number <= 5:
print(number)
number = number + 1
Output:
1
2
3
4
5
Counting Down
timer = 5
while timer > 0:
print(timer)
timer = timer - 1
print("Go")
Counting Matches
Counters can track things:
word = "banana"
index = 0
count_a = 0
while index < len(word):
if word[index] == "a":
count_a = count_a + 1
index = index + 1
print(count_a)
This is more complex than a for loop version, but it shows how counters control positions.
Shorter Updates
Python also supports a shorter way to add one:
count = count + 1
count += 1
Both lines mean the same thing. Beginners may find the first version clearer at first, and that is completely fine.
Practice
Use a counter to print every number from 10 down to 1.