While loops in Python: repeat until the goal is met
When does revenue pass $1 million? A for loop can't answer that, because you don't know how many months to run. A while loop keeps going until the condition says stop.
The big idea
A while loop repeats its block as long as its condition is true, checking the condition before every pass.
See it in code
The condition is tested before each pass. When it becomes false, the loop ends and the program continues below it:
units = 300
months = 0
while units < 1000:
units = units * 2
months = months + 1
print("Passed 1,000 after", months, "doublings:", units)Passed 1,000 after 2 doublings: 1200
300, 600, 1200. After the second doubling the condition units < 1000 was false, so the loop stopped. Its variables keep their final values.
Now the real question. Add each month's revenue to a total, and stop once the total reaches the goal:
price = 38
units = 300
growth = 0.15
goal = 1_000_000
total = 0
month = 0
while total < goal:
month = month + 1
total = total + units * price
units = round(units * (1 + growth))
print(f"Revenue passes ${goal:,} in month {month}")
print(f"Revenue by then: ${total:,}")Revenue passes $1,000,000 in month 19 Revenue by then: $1,008,292
Month 19. Nobody told the loop to run 19 times; it found that number by itself, which is exactly what a for loop couldn't do.
A while loop with an unreachable goal runs forever. A second condition, joined with and, guarantees it stops:
price = 38
units = 300
growth = 0.02
goal = 1_000_000
max_months = 36
total = 0
month = 0
while total < goal and month < max_months:
month = month + 1
total = total + units * price
units = round(units * (1 + growth))
if total >= goal:
print(f"Revenue passes ${goal:,} in month {month}")
else:
print(f"Not reached within {max_months} months (${total:,} so far)")Not reached within 36 months ($591,356 so far)
At 2% growth the goal isn't met in 36 months, so the limit ended the loop. The if afterwards reports honestly which condition stopped it.
While loops fit any "until" problem: keep asking until the input is valid, keep searching until a match is found, keep simulating until a value converges.
Try it yourself
In the second program, change goal to 10_000_000. Ten times the revenue takes only about 16 more months. Then find the smallest growth that still reaches $1 million inside 36 months.
The common mistake
Never changing what the condition tests. If you forget total = total + units * price, then total < goal stays true forever. Every pass must move the loop toward its exit.
What it unlocks
The loop above is an accumulator with an open-ended stopping rule. Its condition is a comparison, often combined with and.