While Loops

Difficulty: Beginner

A `while` loop repeatedly executes a block of code as long as its condition remains True. It is used when the number of iterations is not known in advance and depends on some dynamic condition.

The `break` statement immediately exits the innermost loop, skipping any remaining iterations. The `continue` statement skips the rest of the current iteration and jumps back to the loop condition check. Together, they give you fine-grained control over loop execution.

Infinite loops (`while True`) are intentionally created when you want the loop to run until an explicit `break` condition is met. This pattern is common for menu-driven programs, event loops, and input validation.

A sentinel value is a special value used to signal that a loop should end. For example, reading user input until they type "quit" or accumulating numbers until a negative value is entered. This is a classic use case for while loops.

Code examples

Basic while loop -- countdown

count = 5

while count > 0:
    print(count, end=" ")
    count -= 1

print("Go!")

The loop runs as long as count > 0. Each iteration prints the count and decrements it by 1. When count reaches 0, the condition is False and the loop exits.

break and continue

# break: find the first multiple of 7 above 50
n = 51
while True:
    if n % 7 == 0:
        print(f"First multiple of 7 above 50: {n}")
        break
    n += 1

# continue: print only odd numbers from 1 to 10
print("Odd numbers:", end=" ")
i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i, end=" ")
print()

break exits the loop entirely when the condition is met. continue skips even numbers and goes back to the loop's condition check.

Collatz sequence (3n+1 problem)

n = 12
steps = 0
print(n, end="")

while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1
    steps += 1
    print(f" -> {n}", end="")

print(f"\nSteps to reach 1: {steps}")

The Collatz conjecture says this sequence always reaches 1. The while loop continues until n equals 1, applying the rules each iteration.

Key points

Concepts covered

while loop, break, continue, infinite loop, sentinel value