While Loop & Flowcharts
A while loop repeats a block of code while a condition remains
True. It is especially useful when the number of repetitions is
not known in advance. Flowcharts help us design the loop before translating
the algorithm into Python.
Learning Objectives
- 11.1.2.1 Write program code using a While loop
- 11.1.2.2 Implement a loop algorithm according to a flowchart
While / Iteration
Craig'n'Dave — iteration in the three basic programming constructs. The iteration section begins at about 03:39.
Conceptual Anchor
The Guard at the Door
A while loop is like a guard checking a condition
before each entry. If the condition is True, you
enter the loop body. When the body finishes, you return to the
guard. If the condition becomes False, you leave the loop.
count = 1
count <= 5?
print(count)
count += 1
Anatomy of a While Loop
count = 1
while count <= 5:
print(count)
count += 1count = 1
Create the starting state before the first condition check.
count <= 5
The body runs only when this expression is True.
print(count)
The statements repeated during each iteration.
count += 1
Changes state so the condition can eventually become False.
More precise rule
Something relevant to the condition must eventually change, otherwise the loop may never terminate.
A while loop can run zero times
x = 10
The variable starts at 10.
x < 5
10 < 5 is False.
print(x)
Skipped because the first check is already False.
nothing
The body executes zero times.
x = 10
while x < 5:
print(x)
# No outputWhile Loop Tracer
Notice that the condition is checked one more time after the final successful iteration.
| Check | count before | count <= 5 | Output | count after update |
|---|
Change the Loop
While Loop Flowcharts
| Flowchart Shape | Meaning | Python Equivalent |
|---|---|---|
| Oval | Start / End | Beginning / end of algorithm |
| Parallelogram | Input / Output | input() / print() |
| Rectangle | Process | Assignment / calculation |
| Diamond | Decision | while condition: |
| Arrow | Flow direction | Sequence / loop-back path |
count = 1
while count <= 5:
print(count)
count += 1
# Output:
# 1
# 2
# 3
# 4
# 5
The loop-back arrow is the key
The Yes/True path enters the body and eventually returns to the same decision diamond. The No/False path leaves the loop.
Flowchart Path Tracer
Common While-Loop Patterns
Loop Simulators
Sentinel Accumulator Simulator
Input Validation Simulator
When Should I Use while?
You do not know in advance how many iterations will be needed.
Repetition continues while a Boolean condition remains True.
Input determines when the loop finishes.
Repeat until acceptable input is received.
Preview of the next lesson
When the number of repetitions is known in advance,
a for loop is often more suitable.
Design a while loop with three questions
What values must exist before the first condition check?
Write the Boolean condition controlling repetition.
Which state changes after each iteration?
Identify the state that makes the condition False.
Debugging While Loops
Infinite Loop Detector
Off-by-One Lab
count = 0
while count < 5:
print(count)
count += 1
Output: 0, 1, 2, 3, 4 → 5 iterations.
count = 0
while count <= 5:
print(count)
count += 1
Output: 0, 1, 2, 3, 4, 5 → 6 iterations.
count = 0; while count <= 5: count += 1
Trace Table Builder
x = 20
while x > 2:
x = x // 2
print(x)| Iteration | x before | x after // 2 |
Output |
|---|
Worked Examples
Extension: break
break immediately exits the nearest loop, even when the loop condition
is still True.
while condition:
# repeated statements
if something:
break
# execution continues hereFlowchart → Code Challenge
While Error Lab
Pitfalls & Common Errors
Infinite Loop
If the condition never becomes False, the loop continues indefinitely. Changing a variable is not enough — it must change in a direction that can eventually make the condition False.
Off-by-One Error
< and <= often produce different iteration counts.
Trace the first and last successful checks.
Sentinel Not Updated
When a sentinel controls the loop, a new value must be obtained inside the loop body. Otherwise the condition keeps testing the same old value.
Update Moves the Wrong Way
x += 1 is wrong if the loop needs x to decrease toward zero.
Always compare the update with the stopping condition.
Invalid Starting State
The condition is checked before the first iteration. A starting value may cause the body to run zero times.
Numeric Input Still Needs Conversion
input() returns str. Convert with int()
or float() when the loop compares numeric values.
Pro-Tips for Exams
Loop Tracing Strategy
- Write a trace table with a column for every changing variable and the output.
- Check the condition before every iteration, including the first.
- Remember that one final False check happens after the last successful iteration.
- For flowchart → code, map the decision diamond to the
whilecondition. - Follow the loop-back arrow carefully.
- Ask: what changes, and how will that eventually make the condition False?
Graded Tasks
State the four parts of a common counter-controlled while loop: initialisation, condition, body and update.
Explain how a while loop can execute zero times.
Identify why the following is infinite:
x = 10; while x > 0: x += 1.
Write a countdown using while that prints 10 down to 1 and then
prints "Launch!".
Read integers until the user enters 0. Accumulate and output the total of all non-zero values entered.
Convert a flowchart with the structure Initialise → condition diamond → process → update → loop back into valid Python code.
Trace:
x = 100; while x > 1: x = x // 2; print(x).
Produce a complete trace table and exact output.
Create a number guessing or input-validation program in which
while repeats until a correct/valid value is entered.
Challenge: Collatz sequence
Start with a positive integer. While it is greater than 1: if even divide by 2; if odd multiply by 3 and add 1. Print every value and count the steps.
Exam Practice
Q1: Write the exact output. [3]
x = 10
while x > 1:
x = x // 2
print(x)Reveal marking points
Q2: Explain why this loop never terminates. [2]
x = 1
while x <= 5:
print(x)Reveal marking points
Q3: Write Python code for this algorithm. [4]
Set total to 0 → input number → while number is not 0 →
add number to total → input next number → output total.
Reveal marking points
Q4: How many times does the body execute? [1]
i = 0; while i <= 5: i += 1
Reveal marking point
Self-Check Quiz
while condition is False at the start?
i = 0; while i < 3: i += 1 run?
break do?count = 0, what is the difference between
count < 5 and count <= 5?