Back to Blog
Python

Python Infinite Loop: Control and Safe Usage

python infinite loop: Learn how to create and control infinite loops in Python—when they're intentional, how to exit safely, and how to avoid accidental infinite loops.

while-loopsbreak-statementpython-control-flowgraceful-shutdownevent-loops
A Python while True loop with a break statement, illustrating an intentional infinite loop with a controlled exit.

An infinite loop in Python is a loop that never reaches a terminating condition. In most code that is a bug, but in long-running programs such as servers, daemons, and event listeners, an intentional python infinite loop is the core of the design. The same while True: syntax is used for both cases, and the difference is entirely in how the loop is controlled.

The while True Pattern for Intentional Loops

An intentional infinite loop in Python is almost always written with while True: followed by a body that performs work and then yields control. The condition is a constant, so the loop never ends on its own.

while True: message = queue.get() handle_message(message)

This loop is typical of a worker process: it blocks on queue.get() until a message arrives, processes it, then blocks again. Because the loop blocks on I/O, it does not consume CPU while waiting. The same structure appears in network servers, where the loop accepts a connection, handles it, and returns to wait for the next one.

The key property of an intentional infinite loop is that each iteration either makes progress or blocks. A loop that neither blocks nor makes progress is usually a bug.

Exiting with break and return

An intentional infinite loop needs a controlled way out. The break statement exits the innermost loop immediately, skipping the rest of the body.

while True: command = input("> ") if command == "quit": break execute(command)

Here break ends the loop when the user types quit. Execution continues at the first statement after the loop. If the loop is inside a function, return exits the function entirely, which also terminates the loop. Choose break when the loop should resume after the exit condition; choose return when the loop is the last meaningful work of the function.

A common pattern is a loop with multiple exit conditions. Each condition can be a separate break, or the conditions can be combined into a single check. Separate break statements are easier to read when each condition has a distinct reason.

Avoiding Accidental Infinite Loops

Most accidental infinite loops come from a condition that never becomes false. The classic case is a while loop whose body fails to update the variable that the condition depends on.

count = 0 while count < 10: print(count) # count += 1 # missing increment

Because count never changes, the condition count < 10 stays true forever. The fix is to update the variable in every iteration. The same failure appears when the wrong variable is updated, or when the update is placed after a continue that skips it.

count = 0 while count < 10: if count == 5: continue count += 1

When count reaches 5, continue jumps back to the condition without incrementing, so the loop never advances past 5. This is a subtle variant of the same problem: the loop body does not guarantee progress on every path.

A related mistake is a condition that compares against a value that is meant to change but is reassigned to a constant. If the condition is while status != "done" and nothing in the loop ever sets status, the loop runs forever.

for Loops Over Non-Terminating Iterators

A for loop normally terminates when its iterator is exhausted. An iterator that never raises StopIteration produces an infinite loop, even though the code looks finite.

import itertools for item in itertools.cycle([1, 2, 3]): print(item)

itertools.cycle repeats the sequence indefinitely, so this loop never ends. The same happens with a generator that contains while True: internally. A for loop over such a generator is an infinite loop in disguise.

This is not always a bug. A generator that yields an infinite sequence can be consumed with break once a condition is met:

def integers(): n = 0 while True: yield n n += 1 for value in integers(): if value > 10: break print(value)

This shows a finite use of an infinite generator. The for loop is controlled by break, not by iterator exhaustion.

Runtime Cost and CPU Usage

An infinite loop that does no blocking work will consume one CPU core at full speed. A tight loop with no I/O and no sleep can pin a core, raise power consumption, and slow down other processes on the same machine.

while True: pass # burns a CPU core

The pass body does nothing, so the loop spins as fast as the interpreter allows. If the loop is waiting for a condition that changes in another thread, add a small sleep to yield the CPU:

import time while not ready(): time.sleep(0.01)

A sleep interval of a few milliseconds is usually enough for a polling loop. The tradeoff is latency: a longer sleep means slower detection of the condition. Choose the interval based on how quickly the loop must react.

For loops that block on I/O, such as queue.get() or socket.accept(), no sleep is needed because the blocking call already yields control.

Graceful Shutdown with Exceptions and Signals

An intentional infinite loop should be interruptible. When the user presses Ctrl+C, Python raises KeyboardInterrupt in the main thread. Catching it lets the loop run cleanup code before exiting.

try: while True: process_next_item() except KeyboardInterrupt: save_state() print("shutting down")

The try block wraps the entire loop, so the exception is caught wherever it occurs. This works for interactive scripts. For daemons and services, the operating system may send SIGTERM instead, which requires a signal handler.

import signal running = True def stop(signum, frame): global running running = False signal.signal(signal.SIGTERM, stop) while running: process_next_item()

The handler sets running to False, and the loop exits at the next iteration boundary. This is the standard way to make a long-running loop terminate cleanly when the process is asked to stop. The signal interrupt does not happen inside the loop body; it happens between bytecode instructions, so the loop finishes the current iteration before checking the condition again.

When an Infinite Loop Is the Right Design

Use an intentional infinite loop when the program must run until an external event stops it. A server accepting connections, a worker consuming from a queue, and a background monitor are all examples. In each case, the loop has no natural finite end; it ends only when the process is terminated or a shutdown signal arrives.

If the loop has a natural finite end, a for loop or a while loop with a real condition is clearer. A while True: loop that exits only through break is acceptable, but if the loop always runs a fixed number of times, the explicit condition communicates the intent better.

The decision comes down to whether the termination condition is known before the loop starts. If it is, write it in the condition. If the loop must run until an external event, while True: with a shutdown mechanism is the honest design.

python infinite loop: Practical Usage and Code Examples | RYUSLOG DEV