DSM
50 XP
25 minsBeginner50 XP

While Loops

A for loop knows exactly how many laps it will run before it starts. But some jobs can't know: keep asking the API until it answers, keep halving the error until it's small enough, keep reading input until the user quits. That's while territory — looping on a condition instead of a collection.

What you'll learn

  • Write while loops with conditions that genuinely change
  • Choose between for (known count) and while (unknown count)
  • Build the counter, sentinel, and convergence loop shapes
  • Cap risky loops with a max-attempts guard
  • Diagnose and prevent infinite loops

What

A while loop repeats its block as long as a condition stays True. The condition is checked BEFORE each iteration; the moment it's False, the loop ends. Something inside the loop must eventually change the condition — or the loop never stops.

Why

Data work is full of 'until' problems: retry a flaky download until it succeeds (or you run out of attempts), poll a job until it finishes, iterate a model until it converges. None of these have a known iteration count up front — the defining trait of a while problem.

Where it's used

API retry logic, waiting for a training job to finish, reading paginated results until the last page, numeric methods that run until the answer stabilizes, and interactive menus.

Where this runs in production

NetflixEncoding job polling

After submitting a video for encoding, an orchestrator polls the job status in a while loop — sleep, check, repeat — until the state is 'complete' or 'failed'.

VisaTransaction retry with backoff

A failed authorization is retried while attempts remain and the error is retryable, doubling the wait each time — a while loop with two exit conditions.

DeepMindTraining until convergence

Optimization loops run while the loss keeps improving by more than a tolerance; when improvement stalls, the condition flips and training stops.

Theory

The core ideas, in plain language.

Syntax: `while condition:` followed by an indented block. Python checks the condition; if True, it runs the block, then checks again — and again — until the check comes back False. If the condition is False on the very first check, the body never runs at all.
countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1
print('Done')

Three ingredients of every healthy while loop: a variable initialized BEFORE (countdown = 3), a condition that TESTS it (countdown > 0), and an update INSIDE that moves it toward False (countdown -= 1). Remove the update and this prints 3 forever.

Analogy: Stirring until dissolved

A recipe says 'stir until the sugar dissolves' — not 'stir 40 times'. You check (dissolved yet?), stir, check again. The recipe trusts that stirring changes the situation. A while loop is the same contract: the body must push the world toward the exit condition, or you'll be stirring forever.

Key Concept
for vs while: do you know the count?

If the number of iterations is knowable when the loop starts — every element of a list, exactly N times — use for. If it depends on something that happens DURING the loop — a response arriving, an error shrinking, a user typing 'quit' — use while. When either works, prefer for: it can't forget to advance.

Three classic while shapes: the COUNTER loop (a number walks toward a limit), the SENTINEL loop (run until a special value appears — a 'quit' command, an empty line, a None), and the CONVERGENCE loop (repeat until the change between rounds is smaller than a tolerance — the heartbeat of numerical computing and ML training).
Watch out
Infinite loops

If nothing inside the loop can make the condition False, the loop runs forever — your program hangs at 100% CPU. Common causes: forgetting the update line, updating the wrong variable, or a condition that was never True to begin with (which silently skips the loop — the opposite bug). Before running any while loop, point at the line inside it that moves the condition toward False. If you can't, don't run it. (In a terminal, Ctrl+C interrupts a runaway loop.)

Visual Learning

See the concept, then explore it.

The while loop contract

Check → run → change → check again. Click each node — the 'change' step is the one beginners forget.

Worked Examples

Watch it built up, one line at a time.

Very EasyA counting while loop

Print lap numbers 1 to 3 for a race timer.

Step 1 of 2

Initialize the loop variable before the condition ever runs.

Code
01lap = 1
Practice Coding

Your turn — write the code.

Your task

A server sheds load by processing requests from a queue until either the queue is empty or a processing budget of 50 ms is spent. Complete the while loop with BOTH exit conditions, then report what happened.

Expected output
Processed: 4
Spent: 44 ms
Remaining in queue: 2

Write your solution in the editor on the right, then hit Run.

Exercises

Prove it. Reach 80% to complete the lesson.

Mastery Gate0% / 80% required
Easy0/2 solved

What happens when a while loop's condition is False on the very first check?

Which line is missing? n = 10 while n > 0: print(n)

Medium0/3 solved

Which task is a genuine while problem rather than a for problem?

ScenarioA junior engineer's polling loop is: `while job_status != 'done': job_status = check_status()`. In staging it worked; in production the job FAILED, its status became 'error' forever, and the loop spun all weekend.

What's the robust fix?

A bacteria culture starts at 100 cells and grows 25% per hour. Using a while loop, print how many whole hours until the population exceeds 500. Expected output: 8

Terminates correctly:The loop must stop the first hour the population exceeds 500 (100 → 500.0 is not yet over at hour 7... 1.25^7 ≈ 476.8, 1.25^8 ≈ 596.0)
Counts iterations:hours must increment once per loop pass and print 8
Hard0/2 solved

A convergence loop is `while abs(new - old) > 0.001:`. Under what data condition can this STILL loop forever, even with correct updates?

Collatz: start at n = 27. While n is not 1, replace n with n // 2 if even, else 3*n + 1, counting steps. Print the step count. Expected output: 111

Even/odd branching:Uses % 2 to pick the halving or 3n+1 rule each pass
Correct count:27 reaches 1 in exactly 111 steps
Complete 80% more exercises to unlock.
Interview Prep

How this shows up in real interviews.

When do you reach for a while loop instead of a for loop?

Show model answer

The deciding question is whether the iteration count is knowable when the loop starts. Iterating a collection or repeating exactly N times — for loop, because the count is fixed by the data. Repeating until something happens during the loop — a response arrives, an error drops below tolerance, a user quits — while loop, because only the exit condition is known, not the count. When either would work I default to for, since it advances automatically and can't forget its own update line. In data engineering, for dominates batch processing while while owns the boundary with the outside world: retries, polling, and pagination.

Your service is stuck at 100% CPU and logs show the same two lines repeating. Walk me through diagnosing an infinite loop.

Show model answer

The repeating log lines locate the loop; then I ask the three-ingredient question. One: what does the condition read? Two: does anything in the body WRITE to what it reads? Three: can that write actually reach the exit value? Classic failures are a missing update, updating a different variable than the condition tests (shadowing or a typo), a terminal state the condition doesn't recognize — like a job status of 'error' when the loop only exits on 'done' — or oscillation in a convergence loop where the gap never shrinks. The fix is usually twofold: repair the update, and add a belt-and-braces guard (max attempts or max wall-clock time) so the loop is bounded even when the world misbehaves. Prevention is code review that refuses any unbounded while touching an external system.

Design the loop structure for calling a rate-limited API that can also fail transiently. What conditions and safeguards do you include?

Show model answer

I'd use a while loop with a compound condition: not succeeded, attempts below a cap, and total elapsed time below a deadline. Inside, I attempt the call; on success I set the flag; on a retryable failure (timeout, 429, 5xx) I sleep with exponential backoff — doubling the wait each attempt, often with jitter so parallel workers don't retry in lockstep — and on a permanent failure (auth error, 404) I break out immediately rather than burn attempts on something retries can't fix. After the loop, I check WHICH exit fired: success proceeds, exhaustion raises or alerts with the attempt history. The pattern to name in an interview: bounded retries, exponential backoff, distinguish retryable from permanent errors, and never let the loop's fate depend solely on the remote system behaving.

Common Mistakes to Avoid

1) No update line — the condition can never change, so the loop never ends. 2) Updating a different variable than the one the condition tests. 3) Recognizing only one terminal state ('done') when the world has several ('error', 'cancelled'). 4) Unbounded loops on external systems — always add a max-attempts or deadline guard. 5) Off-by-one between < and <= in counter conditions — trace the final iteration by hand. 6) A condition that's False from the start, silently skipping the body (the invisible twin of the infinite loop).

Ask the AI Tutor

Try these prompts in the AI Tutor panel: • 'Show me three broken while loops and let me find the exit bug in each.' • 'Explain sentinel vs convergence loops with new examples.' • 'Help me design the retry loop for a flaky database connection.' • 'Trace this countdown loop iteration by iteration.' • 'Interview mode: quiz me on for vs while decisions and grade my reasoning.'

Glossary

while loop — repeats its block as long as a condition is True, checked before each pass. Infinite loop — a loop whose condition can never become False. Update line — the statement inside the body that moves the condition toward False. Sentinel — a special value marking 'stop here' in a data stream. Convergence loop — repeats until the change between rounds drops below a tolerance. Max-attempts guard — a second exit condition capping iterations. Polling — repeatedly checking an external status until it changes. Exponential backoff — doubling the wait between retries. .pop(0) — list method removing and returning the first element.

Recommended Resources

• Docs: 'First Steps Towards Programming' in the official Python tutorial — the Fibonacci while loop, from the source. • Read: the tenacity library's README to see production retry policy expressed declaratively — every concept from this lesson appears. • Practice: write a guessing-game loop that halves an interval until it pins a number — you'll rebuild bisection without noticing. • Next in DSM: sometimes the cleanest exit is mid-body — Loop Control gives you break, continue, and pass for surgical control inside any loop.

Recap

✓ while repeats as long as its condition holds; the check happens before every pass. ✓ Every healthy while has three parts: initialize before, test in the condition, update inside. ✓ for = known count; while = loop until something happens. ✓ The three shapes: counter, sentinel, and convergence. ✓ Loops touching the outside world get a max-attempts or deadline guard — always. ✓ To diagnose a hang: find what the condition reads, and prove something writes it toward the exit. Next up: Loop Control. Conditions decide when loops end — break, continue, and pass let you steer from INSIDE the body: exit early, skip a bad record, or hold a place.

scratchpad — preview this lesson's challenge anytime
cooldown.pyPython
Ready
Output

Run your code to see the output here.