Skip to content
🐍For Loops: Walk the Book

For Loops: Walk the Book

beginner Python 9 minfor loopiterationtuple unpacking
What you'll learn
  • for loop
  • iteration
  • tuple unpacking
  • accumulation
  • running total

For Loops - Walk the Book

Scene: end of day, risk wants the book's total exposure. You hold a list of positions - ticker, share count, price. For a three-name book you could add them up by hand. But tomorrow it is thirty names, and next quarter three hundred. A for loop runs the same work whether the book has 3 rows or 3,000: it walks the list one position at a time and executes your code on each.

You read a for loop in the last lesson - it was written for you. Today you write your own.

The shape of a loop

Python
for item in a_list:
    # this block runs once per item
    print(item)

Read it as: "take the items one at a time; call the current one item; run the indented block on it; repeat until the list is exhausted." The indentation is not decoration - it is how Python knows which lines belong inside the loop.

Tuple unpacking - grab every field at once

When each item is a tuple (a fixed group of fields), unpack it into named variables right in the loop header:

Python
book = [("AAPL", 10, 174.55), ("MSFT", 5, 372.15)]
for ticker, shares, price in book:
    print(ticker, shares * price)

Each pass deals one position off the book and drops its three fields straight into ticker, shares and price, in order. This is exactly the line the previous lesson handed you - now you know how it works.

🧠 The running total (accumulation)

The most common loop pattern in finance is the running total: start an accumulator at zero before the loop, then add to it inside the loop.

Python
total = 0.0
for ...:
    total += something   # same as: total = total + something

total += value is shorthand for total = total + value. Forget this line and the accumulator never moves - the classic bug that reports a book worth 0.

Your Task

The starter walks a three-position book and prints each position's value - but the running total never updates (the accumulation line is a no-op), so the summary reports Total notional: 0.00. Add the one line that adds each position's value onto total_notional, and the real book size appears.

Predict before you run: three positions worth 1,745.50, 1,860.75 and 2,906.00 - what should the total be? Add them in your head, then run and check.