While Loops and Sentinel Patterns

Key Takeaways

  • A while loop checks its condition before every iteration, including before the first possible run, so it may run zero times.
  • Every terminating while loop needs a path that changes the condition or executes break.
  • Sentinel loops use a special value to stop input or processing without treating that value as normal data.
  • Counters, accumulators, and flags must be updated in a deliberate order; one misplaced line changes the result.
  • PCEP while-loop traps include off-by-one boundaries, updates skipped after continue, and accidentally processing the sentinel.
Last updated: June 2026

How a while loop runs

A while loop repeats while its condition is truthy. Python checks the condition before entering the loop and again after each completed iteration. If the condition is false the very first time, the body runs zero times.

n = 1
while n < 5:
    print(n)
    n += 2

This prints 1 and 3. After n += 2 makes n equal to 5, the next test 5 < 5 is false, so the loop stops without printing 5.

The most important question for any while loop is: what changes? If the condition can stay true forever, the loop is infinite. In exam snippets the update may sit at the bottom of the body, inside a branch, or be accidentally skipped by continue.

Counters and accumulators

A counter tracks how many times something happened; an accumulator builds a running total, string, or collection.

count = 0
total = 0
while count < 3:
    count += 1
    total += count
print(total)   # 6

Trace it row by row:

Iterationcount beforecount after += 1total after add
1011
2123
3236
stop3condition false6

The answer is 6, not 3, because the loop adds the updated counter each pass.

The sentinel pattern

A sentinel is a special value that means stop. It is not normal data. Common sentinels are 'quit', 'done', '', 0, or -1, chosen so they cannot appear as legitimate data.

total = 0
value = int(input())
while value != -1:
    total += value
    value = int(input())
print(total)

For inputs 4, 7, -1 the total is 11; the sentinel -1 is never added. The classic trap places total += value before the sentinel check, which adds -1.

A second sentinel style uses while True with break, which reads cleanly when the stop test belongs in the middle of the loop:

total = 0
while True:
    text = input()
    if text == 'done':
        break
    total += int(text)

Flags

A flag is a boolean that records whether something happened, such as found = False becoming True when a match appears. Flags often combine with counters in the condition:

index = 0
found = False
while index < len(data) and not found:
    if data[index] == target:
        found = True
    index += 1

Trace the flag separately from the counter so you can tell whether the loop ended because the search succeeded or because the data ran out. Note the short-circuit: when index reaches len(data), not found is never evaluated, which safely avoids an out-of-range index.

Trace-table method

Give every changing variable a column and always add a final stop row.

Checkconditionvalueactiontotal
1value != -14add4
2value != -17add11
3value != -1-1stop11

Writing the condition that fails eliminates most off-by-one errors.

Exam traps

First, a loop runs zero times when its initial condition is false. Second, input() returns a string, so numeric comparisons need int() or float() conversion. Third, continue jumps back to the condition check, so any update below continue is skipped, which can create an infinite loop. Fourth, watch < versus <=; that one character decides the iteration count.

Building strings and lists in a while loop

Accumulators do not have to be numbers. A common PCEP pattern grows a string or a list across iterations.

result = ''
i = 5
while i > 0:
    result += str(i)
    i -= 1
print(result)   # 54321

Trace the order carefully: result collects '5', then '4', down to '1', producing '54321'. If i -= 1 came before the append, the first value added would be '4' and the output would differ. Order of update versus use is the recurring theme of every loop question.

while with else

Like for, a while loop can carry an else clause that runs only when the loop ends because its condition became false, not because a break fired.

n = 0
while n < 3:
    print(n)
    n += 1
else:
    print('clean exit')

This prints 0, 1, 2, then clean exit. Insert a break inside and the else is skipped. Read the while/else as "ran to completion without breaking."

Validating input with a loop

Sentinel and validation loops repeat until acceptable data arrives. A while True with a break reads cleanly when the test naturally belongs mid-body.

while True:
    age = int(input())
    if age >= 0:
        break
    print('try again')

The loop keeps prompting until a non-negative number is entered, then breaks. Remember input() returns a string, so the int() conversion must happen before the numeric comparison.

Decision checklist for any while loop

Ask thisWhy it matters
Is the condition true at entry?A false start means zero iterations
What single statement changes the condition?No change means an infinite loop
Does continue sit above the update?The update is skipped, risking infinity
Is the sentinel checked before it is processed?Prevents counting the stop value
Is the boundary < or <=?Decides whether the limit value runs

Running this checklist before tracing values catches the four mistakes that account for nearly every wrong answer on while-loop items: zero-iteration starts, missing updates, sentinel contamination, and off-by-one boundaries.

Test Your Knowledge

What is printed by this code? n = 2 while n <= 8: n += 3 print(n)

A
B
C
D
Test Your Knowledge

A sentinel value in a loop is best described as:

A
B
C
D
Test Your Knowledge

What is the main risk in this loop? n = 0 while n < 3: if n == 1: continue n += 1

A
B
C
D