MOD-14 · Sequence #14 · Control Flow

Python While Loops

While loops repeat statements as long as a condition remains Truthy. Mastering loop invariants, termination conditions, break/continue statements, and the unique while...else construct is essential for algorithmic correctness.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
i = 1
while i < 4:
    print(i)
    i += 1
else:
    print("Loop finished without break")

Core Principles & Mental Models

1. Loop Termination & Invariants

Preventing Infinite Loops

  • A while loop requires three elements: initialization, condition check, and state progression towards termination.
  • Failing to update state variables inside the loop body causes an infinite loop.
  • Use `break` to exit the loop early when a target condition is met.
  • Use `continue` to skip the remainder of the current iteration and re-evaluate the loop condition.
count = 0
while count < 3:
    print("Iteration:", count)
    count += 1
💡 Key Takeaway: Always verify that every loop branch guarantees progress toward condition failure or break.

2. The while...else Construct

Executing Only on Natural Loop Completion

  • In Python, a while loop can have an optional `else` block.
  • The `else` block executes ONLY if the loop finishes naturally (the condition becomes False).
  • If the loop is exited prematurely via `break`, the `else` block is SKIPPED.
target = 7
curr = 1
while curr <= 5:
    if curr == target:
        print("Found target!")
        break
    curr += 1
else:
    print("Target not found in range 1-5 (No break triggered)")
💡 Key Takeaway: The else block in loops acts as a "no break occurred" completion handler.

Interactive Walkthrough Examples

Binary Search Algorithm with While Loop (Intermediate)

Implementing classic O(log N) binary search using a while loop with pointers.

def binary_search(arr, target):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

data = [10, 20, 30, 40, 50, 60, 70]
print("Index of 50:", binary_search(data, 50))
print("Index of 99:", binary_search(data, 99))

Explanation: Each step cuts search space in half (O(log N)), terminating when low > high.

Common Misconceptions & Exam Traps

Common Pitfall: Off-By-One Errors with Loop Invariants

Array length is 3, valid indices are 0, 1, 2. Accessing items[3] raises IndexError: list index out of range.

Buggy Code
i = 0
items = [1, 2, 3]
while i <= len(items):  # Off by one! i = 3 will raise IndexError.
    print(items[i])
    i += 1
Correct Solution
i = 0
items = [1, 2, 3]
while i < len(items):
    print(items[i])
    i += 1

Exam Trap Note: In exams, prefer `for item in items:` or `enumerate(items)` over manual while indexing.

Conceptual Knowledge Self-Check Quiz

Q1: When does the `else` block of a while loop execute in Python?

  1. Every time the loop finishes an iteration
  2. Only if the loop was terminated with a break statement
  3. Only if the loop terminated naturally without encountering a break
  4. Never, while loops do not support else

In Python while...else, the else block runs only if the loop condition evaluated to False without a break statement.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Prefer `for` loops over `while` loops whenever iterating over known sequences or ranges.
  • ✅ Use while loops primarily when termination depends on dynamic input or convergence criteria.

All 26 Curriculum Modules