Unit 11.1A · Term 1

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.

1. Check condition
2. True → enter body
3. State changes
4. Return and check again
5. False → leave loop
Initialise count = 1
→
Check count <= 5?
→
Body print(count)
→
Update count += 1
After the update, execution returns to the condition. If the condition is False, the loop ends.

Anatomy of a While Loop

count = 1 while count <= 5: print(count) count += 1
1. Initialise count = 1

Create the starting state before the first condition check.

2. Condition count <= 5

The body runs only when this expression is True.

3. Body print(count)

The statements repeated during each iteration.

4. Update 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

Initial value x = 10

The variable starts at 10.

First check x < 5

10 < 5 is False.

Body print(x)

Skipped because the first check is already False.

Output nothing

The body executes zero times.

x = 10 while x < 5: print(x) # No output

While 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

Generated loop


                                    Output
                                    


                                    Summary
                                    

                                

While Loop Flowcharts

START
Oval Start / End
INPUT
Parallelogram Input / Output
PROCESS
Rectangle Assignment / calculation
?
Diamond Condition / decision
Arrow Flow direction
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
Start count ← 1 count ≤ 5? No End Yes print(count) count ← count + 1 loop back
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

Choose a while-loop pattern:

Loop Simulators

Sentinel Accumulator Simulator

Input Validation Simulator

When Should I Use while?

Unknown repetitions

You do not know in advance how many iterations will be needed.

Condition-controlled

Repetition continues while a Boolean condition remains True.

User-controlled stop

Input determines when the loop finishes.

Validation

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

1. Starting state?

What values must exist before the first condition check?

2. Continue while what?

Write the Boolean condition controlling repetition.

3. What changes?

Which state changes after each iteration?

4. How does it stop?

Identify the state that makes the condition False.

Debugging While Loops

Infinite Loop Detector


                            
Follow how the condition changes after each iteration.

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
Predict before choosing.

Trace Table Builder

x = 20 while x > 2: x = x // 2 print(x)
Iteration x before x after // 2 Output
Fill in every cell, then check your trace.

Worked Examples

Choose an example:

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 here

Flowchart → Code Challenge

Choose the Python code that matches the algorithm.

While Error Lab


                            
Identify the most important issue.

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 while condition.
  • Follow the loop-back arrow carefully.
  • Ask: what changes, and how will that eventually make the condition False?

Graded Tasks

Remember

State the four parts of a common counter-controlled while loop: initialisation, condition, body and update.

Understand

Explain how a while loop can execute zero times.

Understand

Identify why the following is infinite: x = 10; while x > 0: x += 1.

Apply

Write a countdown using while that prints 10 down to 1 and then prints "Launch!".

Apply

Read integers until the user enters 0. Accumulate and output the total of all non-zero values entered.

Apply

Convert a flowchart with the structure Initialise → condition diamond → process → update → loop back into valid Python code.

Analyze

Trace: x = 100; while x > 1: x = x // 2; print(x). Produce a complete trace table and exact output.

Create

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
5 2 1

Q2: Explain why this loop never terminates. [2]

x = 1 while x <= 5: print(x)
Reveal marking points
x never changes inside the loop. Therefore x remains 1 and the condition x <= 5 remains True.

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
total = 0 number = int(input("Number: ")) while number != 0: total += number number = int(input("Number: ")) print(total)

Q4: How many times does the body execute? [1]
i = 0; while i <= 5: i += 1

Reveal marking point
6 times.

Self-Check Quiz

Eight quick checks Click each answer to reveal
1. What happens if the while condition is False at the start?
Click to reveal answer
2. How many times does i = 0; while i < 3: i += 1 run?
Click to reveal answer
3. What commonly causes an infinite loop?
Click to reveal answer
4. What does break do?
Click to reveal answer
5. Which flowchart shape represents the loop condition?
Click to reveal answer
6. With count = 0, what is the difference between count < 5 and count <= 5?
Click to reveal answer
7. Why must a sentinel value usually be updated inside the loop?
Click to reveal answer
8. Where does execution go after the loop body finishes?
Click to reveal answer