Index Ai Academy
Phase 0 · ToolsPython core

While loops

About 35 minLooking ahead: some prerequisites aren't done yet

Why this matters

A for loop works through a list you already have. Plenty of jobs aren't like that: retry until the server answers, ask until the reply makes sense, keep going until the goal is reached. An AI agent is exactly this kind of loop. It asks a model what to do next, does it, and stops only when the task is finished. That loop is a while loop, and you'll write one in Phase 1.

  • Write a while loop that repeats until its condition becomes false
  • End a loop early with break, or keep it running with while True
  • Ask the user again until their answer is valid
  • Spot a loop that never ends, and fix it

When you can't count the repeats

A for loop runs once for each item in a list. You know in advance how many times that is.

Often you don't. You stir a sauce until it thickens. You keep a kettle on until it boils. You don't count the stirs; you check a condition and stop when it changes.

A while loop works the same way. It checks a condition, runs its body if the condition is true, then checks again. It stops the first time the condition is false:

savings = 0
weeks = 0
while savings < 500:
    savings = savings + 60
    weeks = weeks + 1

print("weeks needed:", weeks)
print("saved:", savings)

Read it as "while savings are under 500, save another 60 and count a week". After 8 weeks the savings reach 480, still under 500, so the loop runs once more. After week 9 the savings are 540, the condition is false, and Python moves on to the print lines.

Two things must be true for a while loop to work:

  • something inside the loop changes what the condition looks at, here savings;
  • that change eventually makes the condition false.