PythonConditional Statements and LoopsPython loop termination
What is an infinite loop?
Question 53 of 88 · Updated
On this page
- 1. What makes a loop infinite?
- 2. Normal termination versus repeated execution
- 3. Common causes of unintended nontermination
- 4. Prefer a bounded for loop when the count is known
- 5. Can a for loop be infinite?
- 6. Intentional indefinite repetition with an exit
- 7. Avoid skipping progress with continue
- 8. Practical example: limit retry attempts
- 9. Practical example: polling with a deadline
- 10. Cooperative shutdown of a long-running worker
- 11. Reasoning about termination with a decreasing measure
- 12. Debugging a loop that does not finish
- 13. Complexity and resource implications
- Frequently asked questions
- Is while True always an infinite loop?
- Can an infinite loop occur without while True?
- Does break stop every nested loop?
- Is an infinite loop always a bug?
- How can I test code that is supposed to run indefinitely?
- Interview-ready answer
- Official references
An infinite loop is a loop that continues indefinitely because execution never reaches a condition or control-flow path that ends it. In Python, this can happen when a while condition remains truthy, a for loop consumes an unbounded iterator, or a loop repeatedly revisits a state without making progress toward completion.
An infinite loop is not necessarily a programming mistake. Event-driven applications, background workers and command processors may intentionally run until they receive a shutdown request. The distinction is whether indefinite repetition is intended and whether the program has appropriate resource and shutdown controls.
1. What makes a loop infinite?#
The expression while True: starts a loop whose condition cannot itself become false. If its body never executes a break, return, exception or other exit, the loop continues indefinitely.
For example, a body containing only pass would repeat without performing useful work. Such a tight loop can consume substantial CPU time. Do not run that example in an ordinary interactive session merely to observe its behavior.
A less obvious example is a loop that tests whether a counter is positive but never changes that counter. If the counter starts positive and nothing else changes it, the loop condition stays true.
A loop can also be blocked rather than infinite: a single iteration might wait indefinitely for an input, lock or network response. Both can appear to freeze a program, but the causes and remedies differ.
2. Normal termination versus repeated execution#
The previous loop lesson introduced condition-based repetition. Here is a corrected, terminating countdown.
PYTHONn = 3 while n > 0: print(n) n -= 1 print('done')
Output:
3
2
1
doneThe variable n is a nonnegative integer in this example. Every iteration decreases n by one, and the condition is false when n reaches zero.
The key property is progress. With a finite nonnegative starting value and a decrement on each iteration, this loop must terminate if its body completes normally.
Removing the decrement would remove the mechanism that makes the condition false. Changing the decrement to an increment would move the counter in the wrong direction.
3. Common causes of unintended nontermination#
| Cause | Example of the underlying mistake | Correction |
|---|---|---|
| Missing state update | Counter stays positive forever | Update the state on every relevant path |
| Incorrect update direction | Increase a counter that must reach zero | Move toward the terminating boundary |
| Unreachable exit | A break condition never becomes true | Check the exit predicate and its inputs |
| Skipped update | A continue bypasses the progress step | Ensure progress occurs before continuing |
| Equality-only endpoint | A step jumps over the exact target | Use an appropriate inequality or bounded count |
| Unbounded iterator | Source never signals exhaustion | Limit consumption or define cancellation |
| Unbounded retries | Persistent failure is retried forever | Define attempt and time limits |
For instance, starting at zero, adding two repeatedly and waiting for the counter to equal five cannot reach the desired equality. If that is the only exit condition, the loop has no terminating path under those updates. A threshold condition such as stopping when the counter reaches or exceeds five is more appropriate if overshooting is acceptable.
A condition based on floating-point equality can have a related problem because arithmetic results may round. Prefer integer counters for discrete iteration counts and an explicitly chosen tolerance or bounded iteration budget for numerical convergence.
4. Prefer a bounded for loop when the count is known#
PYTHONn=0 for _ in range(4): n+=1 print(n)
Output:
4When exactly four repetitions are required, range(4) expresses the bound directly. There is no manually maintained termination counter in the loop header.
The for statement obtains each item from the range iterator and finishes when that iterator is exhausted. This removes a class of manual counter errors.
It does not guarantee completion of the entire program if an iteration blocks, raises an exception or contains another nonterminating computation. The finite range only bounds the number of items supplied by that iterable.
5. Can a for loop be infinite?#
Yes. A for loop is not inherently limited to a known number of repetitions. It can consume an iterable that supplies values indefinitely.
The standard-library itertools.count creates an unbounded progression. Use itertools.islice to take a finite prefix when demonstrating it.
PYTHONfrom itertools import count,islice print(list(islice(count(10,2),4)))
Output:
[10, 12, 14, 16]The count iterator starts at ten and increases by two without a built-in stopping point. The islice wrapper supplies only the first four values.
Calling list directly on an unbounded count iterator is not a safe demonstration: it attempts to accumulate values without a finite limit. It may exhaust available memory rather than return.
When working with streams, distinguish the lifetime of the source from the amount of data a particular operation should consume. A finite slice, explicit maximum count or a cooperative stop policy can impose a local limit.
6. Intentional indefinite repetition with an exit#
A common pattern is to use while True with a deliberate exit from the body. The following command processor uses a small, finite input so that it can be executed safely.
PYTHONcommands=iter(['ping','stop','ping']) while True: command=next(commands,None) if command is None or command=='stop': break print(command) print('stopped')
Output:
ping
stoppedThe loop exits when it receives the stop command or the iterator is exhausted. The final ping is not processed.
This example assumes that commands are strings and that None is reserved as the exhaustion sentinel. If None could be a legitimate input value, use a distinct sentinel object or another explicit exhaustion mechanism.
In a real interactive application, obtaining a command might block. The shutdown mechanism must account for that waiting operation. Merely adding an exit condition does not make a blocking read cancellable.
7. Avoid skipping progress with continue#
PYTHONdef work(items): remaining=list(items) while remaining: item=remaining.pop() if item<0: continue print(item) work([2,-1,4])
Output:
4
2Each iteration removes an item before deciding whether to skip the remaining processing. Therefore even the continue path makes progress.
The example copies the supplied finite collection and removes items from the end, so it processes them in reverse order. Its purpose is to demonstrate progress on every path, not to prescribe a general queue implementation.
A dangerous alternative would check the last item and immediately continue when it is negative, without removing it or changing the condition. The same negative item could then be examined indefinitely.
Both branches return to the condition after the list has become smaller. This makes the termination argument independent of whether an item is accepted or skipped.
8. Practical example: limit retry attempts#
Repeatedly retrying a failed operation without a stopping policy can cause unintended indefinite execution. A simple attempt budget provides one form of control.
PYTHONdef retry(check, max_attempts): for attempt in range(1,max_attempts+1): if check(): return attempt return None print(retry(iter([False,False,True]).__next__,3)) print(retry(lambda:False,2)) print(retry(lambda:True,0))
Output:
3
None
NoneThe first invocation succeeds on its third attempt. The second exhausts its budget without success. The third performs no attempts because its budget is zero.
The example assumes max_attempts is a nonnegative integer and check is a callable that returns a truth-tested result. A real interface should validate those assumptions. Exceptions from check propagate; the function does not indiscriminately retry exceptions.
This implementation limits the number of calls, not the amount of elapsed time. If check blocks indefinitely, the attempt budget cannot make it return. Production retry policies should distinguish transient failures from permanent failures, use bounded per-attempt timeouts, and consider backoff, jitter, idempotency and an overall deadline. Avoid immediately retrying persistent failures in a tight loop.
9. Practical example: polling with a deadline#
A monotonic clock is appropriate for measuring elapsed time because wall-clock adjustments should not change an ordinary timeout calculation. The following testable example injects a clock and sleep function rather than waiting in real time.
PYTHONdef poll(ready, clock, sleep, timeout, interval): deadline=clock()+timeout while clock()<deadline: if ready(): return True sleep(min(interval,max(0,deadline-clock()))) return False now=[0] def clock(): return now[0] def sleep(dt): now[0]+=dt print(poll(lambda:now[0]>=2,clock,sleep,5,1),now[0]) now[0]=0 print(poll(lambda:False,clock,sleep,3,1),now[0])
Output:
True 2
False 3The first simulated poll becomes ready at time two. The second has a three-unit deadline and never becomes ready.
The example assumes a finite nonnegative timeout, a strictly positive finite interval, a progressing monotonic clock and a readiness function that returns promptly. A real caller can supply time.monotonic and time.sleep, with suitable validation. The locally executed examples use only the deterministic fake clock.
The deadline is checked before starting each readiness call. This is a cooperative polling budget, not a hard interruption guarantee: a slow readiness call or scheduler delay can extend elapsed time, and a successful call begun before the deadline may finish after it. If the application requires a strict completion deadline, use an appropriate timeout or cancellation mechanism for the underlying operation and define how late results are handled.
A positive wait interval helps avoid busy polling. For production code, prefer an event, blocking queue with a timeout, or asynchronous notification when available rather than repeatedly checking a condition without need.
10. Cooperative shutdown of a long-running worker#
PYTHONfrom threading import Event stop=Event() for _ in range(3): if stop.is_set(): break print('tick') stop.set() print(stop.is_set())
Output:
tick
TrueThe standard-library threading.Event represents a flag that threads can set or check. In this deterministic demonstration, the same thread sets the flag, and the next iteration observes it. The finite outer range provides an additional safety bound for the example.
A real worker might receive a stop signal from another thread. Cooperative cancellation requires the worker to check its stop condition at appropriate points and ensure that blocking operations can eventually return. A flag cannot forcibly interrupt arbitrary synchronous code.
Graceful shutdown can also require draining or abandoning queued work according to a defined policy, closing resources and preserving data consistency. Use resource-management constructs such as with or try/finally where appropriate.
11. Reasoning about termination with a decreasing measure#
A useful way to establish termination is to identify a nonnegative integer quantity that strictly decreases on every iteration that repeats.
PYTHONdef halve(n): steps=0 while n>0: n//=2 steps+=1 return steps print(halve(0),halve(1),halve(16))
Output:
0 1 5For nonnegative integer input, each iteration with n greater than zero replaces n with floor(n/2), a strictly smaller nonnegative integer. The loop eventually reaches zero.
The progress measure is n itself. A strictly decreasing sequence of nonnegative integers cannot continue forever. This reasoning assumes that each individual operation completes normally.
For positive n, the iteration count equals its bit length, floor(log2(n)) + 1. Under a unit-cost arithmetic model this is O(log n) iterations. Actual time includes arbitrary-precision integer arithmetic costs.
The test suite additionally checked 1,000 nonnegative inputs from zero through 999, asserting strict progress and comparing the iteration counts against int.bit_length. These tests corroborate the reasoning for that domain; the mathematical argument explains why the loop terminates for other nonnegative integers too.
Not every algorithm has such a simple progress measure. Some need a finite worklist, a visited-state set, a proof of convergence or a defined maximum resource budget.
12. Debugging a loop that does not finish#
Start by identifying whether the code is actively repeating, blocked in one operation or simply processing more input than expected.
- Inspect the loop condition and every path that updates its state.
- Check whether a continue or exception-handling path bypasses the intended progress step.
- Check whether the source is finite and whether a generator or iterator is actually exhausted.
- Inspect representative state values using a debugger or bounded diagnostic logging.
- Look for repeated states that indicate a cycle instead of progress.
- Check external calls for missing timeouts or waiting on resources.
The standard-library pdb debugger supports stepping and inspection. For a locally running terminal program, Ctrl+C commonly requests interruption through KeyboardInterrupt; whether it is handled promptly depends on the environment and the running code. In a notebook, an interrupt-kernel control is commonly available. If a process does not respond, use the appropriate process-management controls while considering unsaved data and ongoing work.
Do not add an arbitrary break solely to hide the symptom. Define why that break is correct for the task, or report that the requested operation could not complete.
13. Complexity and resource implications#
A finite loop over n items typically performs n iterations if there is no early exit. Its actual cost depends on the work in the body.
An infinite loop has no finite total running-time bound under its nonterminating execution assumptions. However, this does not imply that memory usage necessarily grows without limit. A loop that repeatedly updates a fixed-size state can have bounded memory, whereas one that appends each produced value to a list may grow indefinitely.
A tight busy loop may consume CPU continuously. A properly waiting event loop or worker can remain alive for a long time without continuously using a full CPU core.
Time, memory, cancellation responsiveness and external resource usage are separate properties. Design limits for whichever resources matter in the application.
Frequently asked questions#
Is while True always an infinite loop?#
No. It starts with a permanently true condition, but its body can exit using break, return or another control transfer. Whether it actually runs indefinitely depends on the executed path.
Can an infinite loop occur without while True?#
Yes. Any while condition that remains truthy indefinitely can cause one. An unbounded iterator can also cause a for loop to repeat indefinitely.
Does break stop every nested loop?#
No. A break statement exits the innermost enclosing loop to which it belongs. More complex nested-loop exits require an appropriate design.
Is an infinite loop always a bug?#
No. A long-running service or event processor may intentionally repeat until shutdown. It should avoid unnecessary busy waiting and have a deliberate termination mechanism.
How can I test code that is supposed to run indefinitely?#
Test a bounded prefix, inject finite input, use a controllable stop flag or test one iteration separately. For integration tests, use suitable timeouts and isolation. Do not allow a test runner to hang indefinitely.
Interview-ready answer#
An infinite loop repeatedly executes without reaching a terminating condition or exit path. It can occur in a while loop whose condition never becomes false, or in a for loop traversing an unbounded iterator. Common causes include missing state updates, unreachable exits, skipped progress and unbounded retries. Infinite repetition can be intentional for long-running services, but those programs need appropriate waiting, cancellation and cleanup mechanisms. To prevent accidental nontermination, use a finite iteration budget where suitable, verify that every repeating path makes progress, and impose timeouts on blocking operations.
Official references#
- Python Language Reference — The while statement
- Python Language Reference — The for statement
- Python Language Reference — The break statement
- Python Standard Library — itertools
- Python Standard Library — time.monotonic
- Python Standard Library — threading.Event
- Python Standard Library — pdb
Verification note: All nine fenced Python example groups were executed independently on CPython 3.13.5 and matched their documented output. An additional 1,000 nonnegative integer cases confirmed strict progress and the halving iteration count. Intentionally nonterminating examples were explained without executing them. Polling used a simulated clock; real network calls, operating-system interruption behavior and multithreaded cancellation were not tested. The three fenced Mermaid diagrams were manually reviewed, but the Mermaid package and CLI were unavailable locally. Official references are provided under the authorized offline research exception; live documentation, Supabase changelog and public-site rendering were not verified.
References
- 1.Python Language Reference — The while statementdocs.python.org
- 2.Python Language Reference — The break statementdocs.python.org
- 3.Python Standard Library — itertoolsdocs.python.org
- 4.Python Standard Library — time.monotonicdocs.python.org
- 5.Python Standard Library — threading.Eventdocs.python.org
- 6.Python Standard Library — pdbdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design