Brainlag
  1. Library
  2. Concepts
  3. Python

Loops that build a result

A for loop runs the same lines once for each item. Pair it with a total or a new list that grows on every pass to turn many values into one answer.

Python8 min

One block, many times

for price in prices: runs the indented lines once for every item in the list. Each time round, price points at the next item. When the list runs out, the loop ends and Python carries on below it.

range(5) gives the numbers 0 to 4, so for i in range(5): repeats something five times. A while loop repeats as long as its condition is true, which suits "keep going until something happens".

Building up a total

The most common loop pattern: make a result before the loop, then change it a little on every pass. Step through and watch total grow.

Step through it
prices = [3, 5, 2]
total = 0
for p in prices:
    total = total + p
print(total)

total = 0 sits above the loop on purpose. Put it inside and it resets on every pass, so you only ever keep the last price. The same pattern builds a list: start with found = [] and append inside the loop.

Run it: a shopping basket

Run it, then change one thing and run it again.

main.py to run
basket = [("crisps", 1.20), ("cola", 0.90), ("comic", 4.50)]

total = 0
cheap = []
for item, price in basket:
    total = total + price
    if price < 2:
        cheap.append(item)

print(f"Total: {total:.2f}")
print("Under 2:", cheap)

The total that forgets

This should add up every score and print Total: 44. It prints something much smaller. Fix it.

exercise_1.py to run
scores = [12, 7, 20, 5]
for s in scores:
    total = 0
    total = total + s
print("Total:", total)

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.