Skip to content

The while Loop & Indefinite Iteration

In programming, we often encounter tasks where we don’t know the number of repetitions in advance. We might want to keep a web server running until it receives a “shutdown” signal, or keep asking a user for input until they provide a valid email.

This is the domain of the while loop, which implements Indefinite Iteration.


A while loop repeatedly executes a block of code as long as a specific condition evaluates to Truthy.

countdown.py
count = 5
while count > 0:
print(f"Seconds remaining: {count}")
count -= 1 # The 'Update' step
print("Ignition! 🚀")
  1. Test: Python evaluates the condition.
  2. Jump or Execute:
    • If Truthy, it jumps into the indented block.
    • If Falsy, it jumps over the block and continues with the rest of the script.
  3. The Loopback: Once the block finishes, Python jumps back to the Test step.

2. The Concept of the “Loop Invariant”

Section titled “2. The Concept of the “Loop Invariant””

A Loop Invariant is a condition that is guaranteed to be true before and after each iteration of a loop. In the countdown example above, the invariant is that count is always an integer.

Understanding your invariants helps you avoid the most common loop bug: the Infinite Loop.

An infinite loop occurs when the condition never becomes Falsy. This usually happens because:

  1. The “Update” step is missing (e.g., forgetting count -= 1).
  2. The condition is impossible to fail (e.g., while True:).

A Sentinel is a special value used to terminate a loop. It’s common when processing streams of data or user input.

sentinel_pattern.py
items = []
prompt = "Enter a grocery item (or type 'DONE' to finish): "
while True:
entry = input(prompt).strip().upper()
if entry == "DONE":
break # Exit the loop immediately
items.append(entry)
print(f"Your list: {items}")

How does the computer actually “loop”? When Python compiles your code to bytecode, it uses two specific instructions:

  1. POP_JUMP_IF_FALSE: This checks the result of your condition. If it’s False, it tells the CPU to “jump” its instruction pointer to a memory address past the loop.
  2. JUMP_ABSOLUTE: This appears at the very end of your loop block. It tells the CPU to jump back to the memory address of the Test step.

Because these are simple memory jumps, loops are incredibly fast. The overhead comes from the logic you put inside the loop.


In Python, a while loop is generally slower than a for loop for iterating over a collection.

  • while: Requires Python to manually fetch the condition, evaluate it, and manually increment a counter in bytecode.
  • for: Uses the Iterator Protocol (covered in the next chapter), which moves much of the “next item” logic into highly optimized C code.