While Loops in Python: Conditions, break and Infinite Loops

Use a while loop when you don’t know how many repetitions you’ll need.

i = 0 while i < 5: print(i) i += 1# 0 1 2 3 4

That’s the whole distinction from for. A for loop walks through a collection you already have; a while loop repeats until a condition changes — waiting for valid input, retrying a request, reading until a file ends.

⚠️ And it carries a risk for doesn’t: if the condition never becomes false, the loop never stops. This guide covers the syntax, the while True pattern, the else clause, and the three ways a loop silently becomes infinite.

The short version
Use it whenYou don’t know how many repetitions
Use for whenYou have a collection to walk through
Python has nodo-while — the pattern is while True + break
while/elseThe else runs only if no break happened
The riskA condition that never becomes false

The syntax

while condition: # runs while the condition is true

The condition is checked before every iteration, including the first — so a condition that starts false means the body never runs at all.

Three parts have to be right, and forgetting any one causes an infinite loop:

i = 0 # 1. initialise while i < 5: # 2. a condition that can become false print(i) i += 1 # 3. something that changes it

⚠️ Removing line 3 gives an infinite loop. i stays at 0 forever, and the condition never turns false — which is the single most common while bug.

while vs for

The choice is about whether you know the number of repetitions in advance.

# You have a collection → for for fruit in fruits: print(fruit)# You're waiting for something to change → while while not connected: connected = try_connect()

⚠️ This is worth stating plainly because it’s often described backwards: while is not for a known number of repetitions. That’s exactly what for is for.

If you catch yourself writing this, use a for:

i = 0 while i < len(items): # manual index — three things to get wrong print(items[i]) i += 1for item in items: # same result, nothing to get wrong print(item)

Our guide on for loops covers that side.

break and continue

# break — leave immediately n = 0 while True: n += 1 if n >= 3: break print(n) # 3# continue — skip the rest of this pass i = 0 while i < 5: i += 1 if i == 3: continue print(i) # 1 2 4 5

⚠️ With continue in a while, the increment has to come before it. If i += 1 sat at the end of the body, the continue would skip it — and the loop would spin forever on the same value.

while True: the pattern Python uses instead of do-while

Python has no do-while loop. Writing do: is a SyntaxError — the construct doesn’t exist in the language.

When you need the body to run at least once before the condition is checked, the idiom is:

while True: answer = input("Continue? (y/n) ").strip().lower() if answer in ("y", "n"): break print("Please answer y or n.")

The loop is deliberately infinite, and break is the exit. ⚠️ This is idiomatic Python, not a code smell — it’s clearer than duplicating the input call before the loop.

Since Python 3.8, the walrus operator shortens the same thing:

while not (name := input("Name: ").strip()): print("Name can't be empty.")print(f"Hello, {name}")

It assigns and tests in one expression. Our guide on input() covers reading user input safely.

while/else

Like for, a while can have an else — and it means the same thing: the loop finished without break.

i = 0 while i < 3: i += 1 else: print("ran") # ran — condition became false normallyi = 0 while i < 3: if i == 1: break i += 1 else: print("ran") # nothing — break skipped the else

The useful case is a retry loop, where the else means “ran out of attempts”:

attempts = 0 while attempts < 3: if try_connect(): break attempts += 1 else: print("Failed after 3 attempts")

⚠️ Without the else, you’d need a flag to remember whether the loop succeeded or exhausted itself.

⚠️ The three ways a loop becomes infinite

Three causes of infinite while loops in Python: a missing increment, a condition joined by or that can never be false, and comparing floating point numbers with equality

1. Nothing changes the condition

i = 0 while i < 5: print(i) # i is never incremented

The most common one, and usually a forgotten i += 1.

2. A condition that can’t be false

x = 0 while x < 10 or x > 0: # infinite x += 1

This one looks reasonable and isn’t. Once x passes 10, the first half is false — but x > 0 is true, and or only needs one. The condition can never be false for any positive x.

⚠️ With or, check that there’s a value where both sides are false. If there isn’t, the loop is infinite.

3. Floating point that never lands exactly

x = 0.0 while x != 1.0: # infinite x += 0.1

0.1 can’t be represented exactly in binary, so the additions accumulate error:

0.1 + 0.1 + 0.1 == 0.3 # False 0.1 + 0.1 + 0.1 # 0.30000000000000004

The value skips past 1.0 without ever equalling it. ⚠️ Never use != or == with floats in a loop condition — use < or >, which stop correctly.

How to break out when it happens

Ctrl+C in the terminal. In a script running on a server, the process has to be killed — and if it was writing output, the log may be huge by then.

And the defensive habit: when a loop depends on something external — a network call, user input, a file — add a maximum attempt count, so a condition that never resolves still terminates.

Common patterns

# Consume a queue until it's empty queue = [1, 2, 3] while queue: print(queue.pop(0)) # an empty list is falsy, so the loop ends by itself# Retry with a limit attempts = 0 while attempts < 3: if do_something(): break attempts += 1# Read a file line by line with open("data.txt") as f: while (line := f.readline()): process(line)

⚠️ The first pattern works because empty collections are falsy — while queue: reads naturally and needs no length check.

⚠️ while loops on a server

This is where an infinite loop stops being an inconvenience.

On your laptop, Ctrl+C ends it. In a scheduled job or a background worker, nothing does — the process keeps consuming CPU until something kills it.

Three consequences worth knowing:

The CPU limit throttles rather than stops. On shared hosting, a spinning loop doesn’t crash the account — it gets slowed down, so the process stays alive indefinitely, consuming its allowance and degrading everything else on the same account.

The log can fill the disk. A while True that prints on each pass writes megabytes per minute. ⚠️ On a plan with a disk quota, that eventually stops the site from writing anything at all — including sessions and uploads.

And a retry loop with no delay hammers the target. A loop retrying a failed API call as fast as it can may get your server’s IP rate-limited or blocked.

import timeattempts = 0 while attempts < 5: if call_api(): break attempts += 1 time.sleep(2 ** attempts) # 2, 4, 8, 16 seconds

A limit and a growing delay — the standard shape of a retry that doesn’t become an attack.

An infinite loop on shared hosting doesn’t crash — it lingers

The CPU limit throttles the process instead of killing it, so a runaway loop keeps consuming your allowance and slowing everything else down. Copahost VPS plans give you root access to kill it, real logs to find it, and dedicated CPU. From €3.99/month, with snapshots.

See VPS plans

Frequently asked questions

When should I use while instead of for?

When you don’t know how many repetitions you’ll need — waiting for valid input, retrying a request, reading until something ends. ⚠️ for is the one for a known number of repetitions, which is the opposite of what’s often claimed.

Does Python have a do-while loop?

No. Writing do: is a SyntaxError. The equivalent is while True with a break at the point where you’d have put the condition — which is idiomatic Python, not a workaround.

Why is my while loop infinite?

Three usual causes. Nothing changes the condition — a forgotten i += 1. The condition can’t be false — x < 10 or x > 0 is true for every positive x. Or it compares floats with ==, which may never match exactly.

How do I stop an infinite loop?

Ctrl+C in a terminal. ⚠️ On a server there’s nobody to press it — the process has to be killed, and by then the log may be enormous. Add a maximum attempt count to any loop that depends on something external.

What does else do on a while loop?

It runs only if the loop ended because the condition became false, not because of a break. The useful case is a retry loop, where the else means “ran out of attempts without succeeding”.

Why does while x != 1.0 never end?

Because 0.1 can’t be represented exactly in binary, so adding it repeatedly accumulates error and the value skips past 1.0. ⚠️ Never use == or != with floats in a loop condition — use < or >.

Is while True bad practice?

No — it’s the standard Python idiom when the body must run at least once, or when the exit condition is checked in the middle. What matters is that there’s a reachable break. A while True with no exit is the bug, not the construct.

What’s the difference between break and continue?

break leaves the loop entirely; continue skips the rest of this pass and re-checks the condition. ⚠️ In a while, put the increment before any continue — otherwise it’s skipped and the loop spins on the same value.

Can I loop over a list with while?

You can, but for is clearer. The one case where while fits is consuming the list as you go — while queue: queue.pop(0) — because the collection is shrinking, which a for handles badly.

What is the walrus operator in a while?

:= assigns and tests in one expression: while (line := f.readline()):. Available since Python 3.8, it removes the duplicated read that the pattern used to require before and inside the loop.

Why does my loop condition never trigger with user input?

Often whitespace. input() returns exactly what was typed, including a trailing space from a paste, so answer == "y" fails on "y ". Add .strip() — and .lower() if case shouldn’t matter.

What happens to an infinite loop on shared hosting?

It gets throttled, not killed. The CPU limit slows the process rather than ending it, so it lingers — consuming your allowance and degrading the rest of the account. ⚠️ And if it prints on every pass, it can fill the disk quota, which stops the site from writing sessions or uploads.

Conclusion

A while loop repeats until a condition changes — which makes it the right tool when you don’t know how many repetitions you need. When you do know, for is the one.

Three things carry it. Python has no do-while — the idiom is while True with a break, and it’s idiomatic rather than a workaround. The else clause runs only when no break happened, which makes it a “ran out of attempts” branch. And three things cause infinite loops: nothing changing the condition, a condition with or that can’t be false, and comparing floats with ==.

And the reason this matters more on a server: an infinite loop on your laptop ends with Ctrl+C. In a scheduled job, the CPU limit throttles the process instead of killing it — so it lingers, eating its allowance and slowing everything else, while a log that prints on every pass quietly fills the disk.

Any loop waiting on something external should have a maximum attempt count. It’s one variable, and it’s the difference between a failure that stops and one that doesn’t.

Share the Post:
Picture of Gustavo Gallas

Gustavo Gallas

Graduated in Computing at PUC-Rio, Brazil. Specialized in IT, networking, systems administration and human and organizational development​. Also have brewing skills.