Lesson 8 of 10
Most loops you write in real code are variations on a handful of patterns. Learn these three and you will recognise them everywhere.
The accumulator
Build up a running total. Start at zero before the loop, add inside it.
total = 0
for number in range(1, 6):
total += number
print(total)
The key move is that total lives outside the loop. If you created it inside, it would reset
every iteration and you would lose the running value.
Accumulators work on strings too:
word = ""
for letter in "cat":
word += letter.upper()
print(word)
The counter
Count how many items match a condition. Same shape as an accumulator, but you add 1 instead
of the value.
vowels = 0
for letter in "programming":
if letter in "aeiou":
vowels += 1
print(vowels)
The in operator here asks "is this letter one of the characters in that string?" — a quick way
to check membership.
The sentinel value
A sentinel is a special value that means "stop." This is the classic pattern for reading input until the user is done.
total = 0
while True:
entry = input("Number (or 'done'): ")
if entry == "done":
break
total += int(entry)
print(f"Total: {total}")
"done" is the sentinel — it is not data to add up, it is a signal to leave the loop.
Tracking a maximum
A useful variation: keep the biggest value seen so far.
numbers = range(1, 8)
largest = 0
for n in numbers:
if n > largest:
largest = n
print(largest)
Try it yourself
Use an accumulator to sum the numbers 1 through 10, and a counter to count how many of them are even.
Checkpoint
- Accumulators build a running total; initialise them before the loop.
- Counters add
1each time a condition matches. - A sentinel value is a signal to
breakout, not data to process. %gives a remainder —n % 2 == 0is the standard "is it even?" check.
Questions about this lesson
Log in to ask a question.