Course contents
Doing something many times
A loop repeats an action over a sequence, letting you process every price in a list or every row of data without writing the same line a thousand times. Repetition without error is where code beats hand-work.
- Write a for loop over a sequence and a while loop with a condition
- Accumulate a result across a loop
- Loop over a list of prices to compute something
The first chapter promised that code beats hand-work through reliability and scale, and the loop is where that promise is kept. A loop repeats an action over every item in a sequence, so the same few lines process five prices or five million, without you copying anything and without a single transcription error. Almost all real data work is a loop over rows, so this is one of the most important chapters in the early course.
Looping over a sequence
The for loop takes each item of a sequence in turn and runs a block of code for it. This program loops over a week of closing prices twice: once to print each, and once to compute the day-to-day returns.
# A loop repeats work over a sequence, without copying lines by hand.
closes = [1380, 1402, 1395, 1410, 1425]
for day, price in enumerate(closes, start=1): # each item, with a counter
print(f"Day {day}: {price}")
print("Daily returns:")
for i in range(1, len(closes)): # compare each day to the one before
ret = (closes[i] - closes[i - 1]) / closes[i - 1] * 100
print(f" Day {i + 1}: {ret:.2f}%")Day 1: 1380 Day 2: 1402 Day 3: 1395 Day 4: 1410 Day 5: 1425 Daily returns: Day 2: 1.59% Day 3: -0.50% Day 4: 1.08% Day 5: 1.06%
The first loop uses enumerate, which hands you each price together with a counter, so the output numbers the days one to five. The second loop is the interesting one. It uses range(1, len(closes)) to step through the positions from the second day to the last, and for each it computes the return against the previous day, (closes[i] - closes[i-1]) / closes[i-1] * 100. The output is the four daily returns: about 1.59%, then -0.50%, 1.08%, and 1.06%. You have just turned a list of prices into a list of returns, by hand in code, which is exactly the kind of transformation the pandas chapters will later do for you in one line, but it is worth doing the long way once so you understand what that one line is really doing.
Accumulating, and the while loop
Loops often build up a result as they go, a running total, a count, a new list, by updating a variable on each pass. That pattern, starting a variable before the loop and adding to it inside, is how you sum a column or count the days a rule was met. You will use it constantly.
Python also has a while loop, which repeats as long as a condition stays true rather than stepping through a fixed sequence. It suits situations where you do not know in advance how many times to repeat, though it comes with a caution: if the condition never becomes false, the loop runs forever, a classic beginner bug. For marching through prices and rows, the for loop is what you will reach for almost every time.
The deeper point is the one from the first chapter, now made concrete. The second loop computed four returns here, but the identical code would compute four thousand from four thousand prices, in the same instant and with the same accuracy. That is the moment coding starts to pay off: a calculation you could just about do by hand for a week runs in an instant for a decade.
What to carry forward
A loop repeats work across a sequence: the for loop takes each item in turn (with enumerate for a counter and range for positions), loops often accumulate a result by updating a variable each pass, and the while loop repeats while a condition holds. Turning a list of prices into daily returns by looping is exactly what the data tools will later do in one line, and doing it the long way once shows you what that line means.
You have now met the core pieces of the language: values, containers, decisions, and repetition. The next chapter shows how to package logic into reusable functions, so your growing programs stay organised.