closes = [185.4, 187.2, 184.9]
for c in closes: # c becomes 185.4, then 187.2, then 184.9
print("close:", c)
# -> close: 185.4
# -> close: 187.2
# -> close: 184.9close: 185.4
close: 187.2
close: 184.9
A for loop runs the same block of code once for every item in a list. You write the block once and Python repeats it, handing you one item at a time.
I show four things here: the loop variable, indentation, zip for walking two lists in step, and a running total.
Three closing prices. One loop.
close: 185.4
close: 187.2
close: 184.9
c is the loop variable. The name is yours to pick. The line for c in closes: ends in a colon, and the indented line below it is the body: the part Python repeats.
Indentation decides what belongs to the loop. Move a line out and it runs once, after the loop has finished.
inside : 185.4
inside : 187.2
inside : 184.9
outside: 184.9
The last line prints 184.9 because c keeps the value it held on the final pass.
zip walks two lists together and hands you one item from each.
Mon 185.4
Tue 187.2
Wed 184.9
Two loop variables now, d and c, filled position by position.
To accumulate a total, create it before the loop and add to it inside.
running total: 185.4
running total: 372.6
running total: 557.5
185.83333333333334
Move total = 0.0 inside the loop and it is reset on every pass:
Three holdings, each with a price and a share count. The value of one holding is price times shares.
tickers = ["AAPL", "MSFT", "NVDA"]
prices = [185.40, 410.20, 128.75]
shares = [10, 4, 20]
total = 0.0
for tkr, px, n in zip(tickers, prices, shares): # zip handles three lists too
value = px * n
total += value
print(tkr, value)
# -> AAPL 1854.0
# -> MSFT 1640.8
# -> NVDA 2575.0
print("total", total) # -> total 6069.8AAPL 1854.0
MSFT 1640.8
NVDA 2575.0
total 6069.8
Add a fourth stock to all three lists and the loop values it too. Nothing else changes.
Print each holding’s weight: its value divided by the portfolio total. The total has to exist before you can divide by it, so this takes two passes.
Before rounding, the weights sum to 1, so each one is the share of the portfolio held in that stock.