livepython.net
CHAPTER 10For Loops
10.3  SUM AND COUNT

Sum and Count with a Python for Loop

Add Up Numbers with a Running Total

To add up numbers in a for loop, keep a running total: a variable that starts at 0 and grows by each item with += (chapter 5). This is called the accumulator pattern ("accumulate" means "collect bit by bit").

PYTHONedit me
prices = [40, 25, 60]
total = 0
for price in prices:
    total += price
print("Total:", total)
OUTPUT
Total: 125

Think of it like a shop's cash register: it starts at 0, and every item the cashier scans is added to the amount on the screen.

The three steps

  1. Before the loop: start the total at 0.
  2. Inside the loop: add the current item, total += price.
  3. After the loop: use the result, here print().

Watch the total grow by printing it inside the loop:

PYTHONedit me
total = 0
for price in [40, 25, 60]:
    total += price
    print("so far:", total)
OUTPUT
so far: 40
so far: 65
so far: 125

Add up input

With range() and input() from the last topic, you can add numbers the user types:

PYTHONedit me
total = 0
for i in range(3):
    total += int(input())
print("Total:", total)
OUTPUT
Total: 35

For a list you already have, sum(prices) from chapter 9 gives the same answer in one go. The loop shines when the numbers arrive one at a time, or when you only want to add some of them (next lesson).

Common mistakes

  • Forgetting total = 0: Python stops with a NameError, because total += price needs a value to add to.
  • Putting total = 0 inside the loop: the total is reset every time and ends up as the last price only.

Start at 0 before the loop, add with += inside it, use the total after it.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

for n in [5, 10, 15]: total = 0 total += n print(total)
Your turn! What will this code show on the screen?

Count with an if Inside the Loop

To count how many items match a rule, start a counter at 0 and add 1 each time an if inside the loop is True.

PYTHONedit me
marks = [72, 38, 91, 25, 60]
passed = 0
for mark in marks:
    if mark >= 40:
        passed += 1
print("Passed:", passed)
OUTPUT
Passed: 3

Think of it like a referee with a clicker: they watch every player run past, and click only when a player crosses the line.

The rules

  • The counter starts at 0, before the loop.
  • count += 1 goes inside the if, so it only runs for matching items.
  • Print the count after the loop, at the left edge.

Mind the indentation: the loop's block is 4 spaces in, and the if block is 8 spaces in.

Count and add in one loop

One loop can do several jobs at once. Here it counts the big spenders and adds up their money:

PYTHONedit me
bills = [120, 800, 45, 1500]
big = 0
big_total = 0
for bill in bills:
    if bill > 500:
        big += 1
        big_total += bill
print(big, "big bills, worth", big_total)
OUTPUT
2 big bills, worth 2300

Count characters

The same pattern works on a string. Here in from chapter 9 checks whether each letter is in a list of vowels:

PYTHONedit me
word = "education"
vowels = ["a", "e", "i", "o", "u"]
count = 0
for ch in word:
    if ch in vowels:
        count += 1
print("Vowels:", count)
OUTPUT
Vowels: 5

Common beginner doubt: "Isn't len() a counter too?" Yes, but it counts everything. A loop with an if counts only what you choose.

A counter starts at 0 and goes up by 1 inside an if in the loop.

your turnType the output

Type what this prints

count = 0 for n in [4, 7, 10, 3]: if n > 5: count += 1 print(count)
Read the code line by line, then type the output exactly.
your turnFill the gap

Count the even numbers

evens = 0 for n in [2, 5, 8, 11]: if n % 2 == 0: ? print(evens)

It should print: 2

Which piece makes this code work?

Find the Largest or Smallest Value

To find the largest value with a loop, remember the best one so far. Start with the first item, then compare every item with it and keep the bigger one.

PYTHONedit me
scores = [42, 87, 65, 91, 30]
best = scores[0]
for score in scores:
    if score > best:
        best = score
print("Best score:", best)
OUTPUT
Best score: 91

Think of it like a high jump contest: the judge remembers the best jump so far, and only changes it when someone jumps higher.

The rules

  • Start best with the first item, scores[0].
  • Inside the loop, if score > best: then best = score.
  • For the smallest value, flip the comparison to <.

Why not start at 0?

Starting at 0 looks fine, until every number is negative:

PYTHONedit me
temps = [-5, -2, -9]
warmest = 0
for t in temps:
    if t > warmest:
        warmest = t
print(warmest)
OUTPUT
0

The answer should be -2, but no temperature is bigger than 0, so warmest never changes. Starting with a real item from the list is always safe.

With input

max() from chapter 9 does this for a list in one step. But when numbers arrive one by one from input(), the loop is the tool. Read the first number before the loop:

PYTHONedit me
best = int(input())
for i in range(3):
    n = int(input())
    if n > best:
        best = n
print("Largest:", best)
OUTPUT
Largest: 40

Keep the best so far: start with the first item, swap when you find a bigger one.

your turnPredict the output

What will this print?

low = 50 for n in [70, 20, 90, 35]: if n < low: low = n print(low)
Your turn! What will this code show on the screen?
your turnPick the right idea

Why start best with the first item instead of 0?

Think about it, then pick one.

Build a New List or String in a Loop

A loop can also build something new: start with an empty list [] or an empty string "", and add a piece in every iteration.

Think of it like threading beads on a string: you start with an empty thread and add one bead at a time.

Build a list with append()

append() from chapter 9 adds one item to the end of a list:

PYTHONedit me
marks = [72, 38, 91, 25]
passed = []
for mark in marks:
    if mark >= 40:
        passed.append(mark)
print(passed)
OUTPUT
[72, 91]

The new list passed keeps only the marks you chose. The old list doesn't change.

Build a string with +=

+= joins text to a string (chapter 5), so a loop can build a word piece by piece:

PYTHONedit me
word = "banana"
result = ""
for ch in word:
    if ch != "a":
        result += ch
print(result)
OUTPUT
bnn

Reverse a string

Put each new character in front of the result instead of behind it, and the string comes out backwards:

PYTHONedit me
word = "Sunny"
backwards = ""
for ch in word:
    backwards = ch + backwards
print(backwards)
OUTPUT
ynnuS

Step by step: "S", then "uS", then "nuS", then "nnuS", then "ynnuS".

The pattern

GoalStart withInside the loop
a totaltotal = 0total += n
a countcount = 0count += 1
a new listitems = []items.append(x)
a new stringtext = ""text += ch

Every one has the same three steps: start before the loop, grow inside it, use the result after it.

Start empty before the loop, add a piece inside it, use the result after it.

your turnFill the gap

Keep only the long names

names = ["Sunny", "Al", "Rocky", "Jo"] long_names = [] for name in names: if len(name) > 3: ? print(long_names)

It should print: ['Sunny', 'Rocky']

Which piece makes this code work?
your turnType the output

Type what this prints

price = 7.5 print(f"Cost: {price * 2:.2f}")
Read the code line by line, then type the output exactly.

Practice: Sum and count

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 85.Python Program to Find the Sum of N NumbersEasySolve
  2. 86.Python Program to Count the Vowels in a WordMediumSolve
  3. 87.Python Program to Find the Largest of N NumbersMediumSolve