ReviseAlgo Logo

Control Flow

While Loops

Condition-based iteration

Interview: Loop control

Last Updated: June 12, 2026 5 min read

The while loop repeats as long as a condition is true. Use it when the number of iterations is unknown in advance — for known counts, prefer for with range().

Common Patterns

  • Counter loop: Increment/decrement until condition met
  • Input loop: while True: with break on quit
  • Retry pattern: Loop with attempt counter and delay
  • Event loop: Process events until shutdown signal
  • while-else: else runs if loop ends without break (rarely used)

Infinite Loop Warning

Always ensure the while condition eventually becomes False, or include a break. Forgotten counter increments or incorrect break conditions are the #1 cause of infinite loops in Python.

Use Cases

Retry logic with exponential backoff

Interactive input loops (prompt until valid)

Game/event loops that run until a condition changes

Reading streams until EOF or sentinel value

Common Mistakes

Creating infinite loops by forgetting to update the condition variable

Using while when a for loop would be more appropriate

Not including a break or max attempts in while True loops

Forgetting the while-else clause executes only when no break occurs