For loops in Python: forecast a year in six lines
What will the first year look like if sales grow 15% a month? You could work out twelve months by hand. Or you could describe one month and let a loop do the other eleven.
The big idea
A for loop runs the same block once for each value in a sequence, handing your code that value through a loop variable.
See it in code
range(1, 4) produces 1, 2, 3. The loop runs its indented block once per value, with month holding each in turn:
for month in range(1, 4):
print("Month", month)Month 1 Month 2 Month 3
Three values in, three lines out. The loop variable is the hook everything else hangs on.
A loop's body can do several steps, and it can change variables that live outside it. Here each pass reports the month, then grows sales for the next one:
price = 38
units = 300
growth = 0.15
for month in range(1, 4):
revenue = units * price
print(f"Month {month}: {units} tees, ${revenue:,}")
units = round(units * (1 + growth))Month 1: 300 tees, $11,400 Month 2: 345 tees, $13,110 Month 3: 397 tees, $15,086
units carries over from one pass to the next, so each month starts where the last one ended. The order matters: report this month first, then grow.
Change one number in range and the same body forecasts a full year. A second loop shows the other common form, iterating directly over a list:
price = 38
units = 300
growth = 0.15
monthly_revenue = []
for month in range(1, 13):
monthly_revenue.append(units * price)
units = round(units * (1 + growth))
for quarter_end in [3, 6, 9, 12]:
print(f"Month {quarter_end}: ${monthly_revenue[quarter_end - 1]:,}")
print(f"Year one: ${sum(monthly_revenue):,}")Month 3: $15,086 Month 6: $22,990 Month 9: $34,960 Month 12: $53,200 Year one: $331,398
The first loop builds twelve values with range. The second reads four of them by looping over a list. Monthly revenue more than quadruples across the year.
Nothing here is specific to sales. Swap the body and the same loop walks the codons of a DNA strand, the bars of a price series, or the cards a web page needs to render.
Try it yourself
Change growth to 0.10 and guess how far year one falls before you run it. A third? Five percent? The real drop is about 27%, because growth compounds. Then print every month instead of only the quarter-ends.
The common mistake
Misreading where range stops. range(1, 12) yields 1 through 11, which is eleven months, not twelve: the stop value is excluded. For months 1 to 12, write range(1, 13).
What it unlocks
Learn the three-argument form of range(), keep a running figure with an accumulator, and when you don't know the number of passes in advance, use a while loop.