Learn by reading through in order

while Loops and Avoiding Infinite Loops

Pick up Python while loops, dodge infinite loops, and learn when to choose while over for — every example runs in your browser.

The previous for chapter focused on loops where the count or target is known up front.

The while statement covered here is a loop that repeats "as long as a condition holds", and it's used when the number of iterations isn't known in advance. Retry handling, queue draining, game loops — it shows up everywhere in real code.

while basics — repeat while the condition is True

while condition: runs the block repeatedly as long as the condition is True. Every time the loop spins, the condition is re-evaluated, and the moment it becomes False, the loop exits.

It's similar to for in shape, but instead of pulling from a target, it loops on the condition itself.

The while evaluation cycle
Startevaluate conditionrun bodyupdate variableEndTruere-evaluateFalse

Condition → if True, run the body → check the condition again → exit when False. The cardinal rule of while: drive the condition toward False inside the body.

# The basic shape — print 0 through 4
count = 0
while count < 5:
    print(count)
    count += 1
# 0 / 1 / 2 / 3 / 4

# Drain remaining tasks from a queue
tasks = ["send mail", "backup", "deploy"]
while tasks:
    task = tasks.pop(0)       # take from the front
    print(f"processing: {task}")
# processing: send mail / processing: backup / processing: deploy

The second example relies on the fact that while tasks: flips to False the moment the list is empty, using the truthiness rules from earlier (an empty list is False).

Loop until there are 0 inquiries left.

① Define remaining = 3 (the count of remaining items).

② Use while to print "Handling X remaining" while remaining > 0, decrementing remaining by 1 each time.

③ After the loop exits, print "All handled".

(The explanation appears once you run the code correctly.)

Python Editor

Run code to see output

Avoiding infinite loops — always provide a termination condition

The biggest pitfall with while is the infinite loop. If you forget the update that flips the condition to False, the program never stops. Even in this in-browser console, that freezes the page until it times out a few seconds (or tens of seconds) later.

# Bad: n never changes inside the body, so it never ends
# n = 10
# while n > 0:
#     print(n)
# (Don't run this — it freezes the browser / times out)

# Good: decrement n each time so the condition eventually becomes False
n = 10
while n > 0:
    print(n)
    n -= 1
The pattern for building a termination condition
while n > 0run bodyn -= 1updatedends eventuallywhile n > 0run bodyno updateinfinite loop

Whenever you write a while, check that you can answer "how does the condition become False?"

Before you run it, point at the code and confirm that every variable in the condition is updated somewhere in the loop body.

Implement a countdown from 5.

① Define count = 5.

② Inside while count > 0:, print count and decrement it with count -= 1.

③ After the loop exits, print "LIFT OFF!".

Python Editor

Run code to see output

Using break and continue inside while

The break / continue you saw with for work the same inside while.

Even while the condition is True, break decisively exits the loop and continue redoes the current iteration — these are the typical patterns.

break and continue inside while
while condif condbreakout of loopwhile condif condcontinuere-evaluate condTrueTrueexitTrueTrueback
# Simulating retries: up to 5 attempts, break when found
responses = [None, None, "OK", "OK", "OK"]   # mock external API responses
attempt = 0
found = False
while attempt < 5:
    attempt += 1
    response = responses[attempt - 1]
    if response is None:
        print(f"attempt {attempt}: no response, retrying")
        continue   # skip the rest of this iteration
    print(f"attempt {attempt}: got response {response}, done")
    found = True
    break          # success, exit the loop

if not found:
    print("reached the maximum number of attempts")

Putting attempt += 1 at the top of the loop is the key. With this layout, even if continue or break exit early, the counter never gets skipped, so the "up to 5 attempts" guarantee holds.

Write a password retry loop using a predetermined list of results (no randomness).

① Prepare attempts = ["wrong", "wrong", "right", "wrong"] (the attempt outcomes).

② Start with i = 0 and loop with while i < len(attempts):.

③ Inside, increment i by 1 (at the top), read one result, and:

 - If "right", print "Authenticated on attempt X" and break.

 - Otherwise print "attempt X failed".

④ Hold a boolean in a found flag, and after the loop print "Locked out" only when no correct answer was found.

Python Editor

Run code to see output

Choosing between for and while

for and while are both loops, but they suit different situations. When you can't decide, recall this table.

When you want to…Best fitWhy
Process every element of a list, dict, etc.forTop-to-end iteration reads naturally
Repeat exactly N times from 0 to N-1for + range(N)The count is stated explicitly as a number
End on a complex condition where the count isn't knownwhileThe condition itself drives the loop
Retry until an external response succeedswhile + breakYou can exit immediately on success
Process user input or a queue until emptywhileIt naturally ends the moment it goes empty

In this article, we covered the basics of while, the termination conditions that prevent infinite loops, controlling flow with break / continue, and how to choose between for and while.

With if / for / while covered, you've learned the fundamental control flow.

QUIZ

Knowledge Check

Answer each question one by one.

Q1What does this code print?
n = 3
while n > 0:
print(n)
n -= 1

Q2What's the most important thing to do to avoid an infinite loop in while?

Q3Which is the most appropriate way to choose between for and while?