Looping over text, and keeping a total
🌍 In real life. To count the money in your wallet, you start at 0 and add each note as you take it out: 0, then 100, then 150, then 170. You don't remember every note, only the running total. When the wallet is empty, the total is the answer.
Programs add things up the same way, and a for loop can walk through a string just as easily as through numbers.
The idea in one sentence: a for loop can walk through a string one character at a time, and an accumulator is a variable made before the loop that collects the answer inside it.
Its words:
- accumulator: a variable that builds up a result lap by lap, like
total - counter: an accumulator that adds 1 each time something is found
- empty string
"": the starting value when you build up text
Step by step, the accumulator pattern:
- Before the loop:
total = 0. - Inside the loop: add the current value,
total += n. - After the loop:
totalholds the answer, ready to print.
for ch in "cat":
print(ch)A very common loop job is adding things up. Make a variable for the total before the loop, starting at 0. Inside the loop, add to it. After the loop, it holds the answer. This is called an accumulator.
total = 0
for n in range(1, 4):
total += n
print(total)Counting works the same way: start at 0 and add 1 each time you find what you're looking for.
word = "banana"
count = 0
for ch in word:
if ch == "a":
count += 1
print(count, "a's in", word)You can build up a string as well. Start with the empty string "". Putting each new letter in front turns the word around:
word = input("Word: ")
backwards = ""
for ch in word:
backwards = ch + backwards
print(backwards)Why before, inside, after? Each part runs a different number of times. The line before the loop runs once, so the total starts at 0 once. The line inside runs once per lap. The line after runs once, when the total is complete. Put a line in the wrong part, and it runs the wrong number of times.
What it costs. One lap per character or number, so the work grows with the length. Building a string with + makes a new string every lap; that's fine for words, but for very long text Chapter 8 shows a faster way with a list and "".join().
Mistakes and edge cases.
- Starting the total inside the loop.
total = 0inside the block resets it every lap, so only the last value survives. - Printing inside the loop.
print(total)indented under theforshows a running total every lap instead of one answer. - Forgetting to start it.
total += nwith nototal = 0before givesNameError: name 'total' is not defined. - Capital letters. Counting
"a"misses"A". Comparech.lower() == "a"to count both.
Quiz
What does this print?
for ch in "hi": print(ch * 2)What does this print?
count = 0 for ch in "hello": if ch == "l": count += 1 print(count)What does this print?
s = "" for ch in "abc": s = ch + s print(s)Why does
total = 0go before the loop and not inside it?- Inside, it would reset the total to 0 on every lap
- Python doesn't allow = inside a loop
- It makes the loop run faster
This should print 6, but prints 3. Which line is wrong?
for n in range(1, 4): total = 0 total += n print(total)
Coding tasks
Ask for a whole number
n. Print the sum 1 + 2 + … +n.Ask for a word in lowercase. Print how many vowels it has (a, e, i, o, u).
Ask for a whole number (read it as text, don't convert it). Print the sum of its digits. For example,
123gives 6.