Repeating a block for each item
A for loop runs its indented block once for every item of a collection, and gives each item a name for that pass. Here the collection is a list, written with square brackets and commas (lists get a topic of their own later). The syntax mirrors if: a colon at the end of the first line, and an indented block under it.
prices = [184.25, 184.5, 184.0]
for price in prices:
print(price) # 184.25, then 184.5, then 184.0range: counting without a list
range(n) produces the whole numbers 0 up to n - 1: the stop value is not included, which is why range(5) has five numbers. range(start, stop) begins where you say, and range(start, stop, step) skips by step, which may be negative to count down. Use it when you need to repeat something a number of times, or to walk through positions.
# range counts, and stops before the stop value
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 10, 3))) # [2, 5, 8]
print(list(range(3, 0, -1))) # [3, 2, 1]The accumulator pattern
Most loops follow one pattern: start a variable before the loop, update it inside the loop, use it after. total += price * quantity is shorthand for total = total + price * quantity. Here each item of the list is a pair, and the loop line names both halves at once (the next topics explain this unpacking properly).
# Accumulate a total over the trades
trades = [(184.25, 200), (185.0, 100), (183.5, 50)]
total = 0.0
for price, quantity in trades:
total += price * quantity
print(total) # 64525.0Looping over positions
Sometimes you need to compare each item with the one before it. Loop over the positions with range(1, len(prices)): it starts at 1, so prices[i - 1] is always valid. len() gives the number of items, and prices[i] picks the item at position i, counting from 0.
# Compare each price with the one before it
prices = [184.0, 184.5, 184.25, 185.0]
ups = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
ups += 1
print(ups) # 2Building a list as you go
To collect one result per pass, start with an empty list [] and call .append(value) inside the loop. Price ladders, running totals and signals per day are all built this way. The list is returned (or used) after the loop ends.
# Build a list of prices, one per tick level
start, tick = 184.0, 0.25
ladder = []
for level in range(4):
ladder.append(start + level * tick)
print(ladder) # [184.0, 184.25, 184.5, 184.75]Next up: while loops, break and continue, for repeating until a condition changes instead of for a fixed number of items.
Lab · what's graded
- Add up the value of many trades with
total_notional25 pts - Lay out price levels with
price_ladder25 pts - Count the days the price rose with
count_up_days25 pts - Keep a running total with
running_total25 pts