Decisions & Loops · Lesson 53

While Loops

While Loops is part of Python control flow: the rules that decide which statements execute and how many times they execute.

ConceptWorked examplePracticeKnowledge check
Textbook walkthrough

What While Loops actually means

While Loops is part of Python control flow: the rules that decide which statements execute and how many times they execute. Conditions convert program state into True/False decisions, while loops repeat a block until the iteration source is exhausted or a stopping condition is reached.

While Loops matters because control flow turns static expressions into behaviour: it decides which path runs, which records are processed and when repetition stops. Small mistakes here can skip cases, double-count values or create non-terminating loops.

Deeper walkthrough

Read While Loops as a mechanism, not a recipe

Treat this as a sequence of observable decisions rather than one opaque command. Stage 1: Evaluate a condition to a truth value. Stage 2: Execute only the selected indented branch. Stage 3: For loops iterate over values from an iterable; while loops repeat while a condition remains true. Final checkpoint: Ensure every loop has a clear progression and stopping argument.

Mechanism

Follow the transformation

Evaluate a condition to a truth value.

Execute only the selected indented branch.

For loops iterate over values from an iterable; while loops repeat while a condition remains true.

Evidence

Know what would convince you

  • Run the operation on a tiny literal input and write the expected type/value before executing it.
  • Inspect the relevant object state before and after the operation, especially when mutable objects are involved.
Useful distinctionif / elif / else: Choose one path based on conditions.
Click a stage to inspect what happens, what changes, and what should be checked before moving on.
Stage 1

Evaluate a condition to a truth…

Evaluate a condition to a truth value. For While Loops, identify the exact state before this stage, the operation or rule applied here, and the observable state afterwards so the mechanism remains inspectable.

State focus: identify exactly what changed at this stage and what observable evidence confirms that change.
How it works

Trace the mechanism step by step

  1. Evaluate a condition to a truth value.
  2. Execute only the selected indented branch.
  3. For loops iterate over values from an iterable; while loops repeat while a condition remains true.
  4. break exits the nearest loop; continue skips to the next iteration.
  5. Ensure every loop has a clear progression and stopping argument.
Worked demonstration

Make the concept concrete

Demonstration

Python example

# Step 1 — Compute the right-hand expression and store its result in `transactions` for the next step.
transactions = [120, 980, 45, 1500, 260]
# Step 2 — Compute the right-hand expression and store its result in `flags` for the next step.
flags = []
# Step 3 — Iterate through the collection so the indented block is applied once for each item.
for amount in transactions:
    # Step 4 — Evaluate this condition and execute the indented branch only when the condition is true.
    if amount >= 1000:
        # Step 5 — Execute this statement and inspect how it changes the current value, object or program state.
        flags.append("high")
    # Step 6 — Check this alternative condition only when the earlier branch did not run.
    elif amount >= 500:
        # Step 7 — Execute this statement and inspect how it changes the current value, object or program state.
        flags.append("review")
    # Step 8 — Handle the remaining case that was not captured by the preceding condition(s).
    else:
        # Step 9 — Execute this statement and inspect how it changes the current value, object or program state.
        flags.append("normal")
# Step 10 — Display the current value explicitly so the result/state can be inspected during execution.
print(flags)
Expected / illustrative result
['normal', 'review', 'normal', 'high', 'normal']
Interpret the result.

For While Loops, connect the displayed result to the specific input and mechanism above; independently verify one value/state change rather than treating successful execution as proof.

Distinctions & related ideas

Know what this is — and what it is not

if / elif / elseChoose one path based on conditions.
forIterate over items from an iterable or range.
whileRepeat while a condition stays true.
break / continueChange the normal loop flow by stopping or skipping an iteration.
Use deliberately

When it is appropriate

Use While Loops when the program genuinely needs this language behaviour and you can state the input object, resulting value/state and expected failure behaviour.

Boundary conditions

When to stop or reconsider

Choose a clearer built-in, data structure or control-flow pattern when it expresses the intent more directly; stop if implicit conversion, mutation or hidden state makes the behaviour hard to reason about.

Common mistakes

Failure modes to recognise

  • Applying the operation to an incompatible type or assuming Python will silently coerce values the way you intended.
  • Confusing a returned value with an in-place mutation or other side effect.
  • Testing only the happy path and missing empty, boundary or invalid inputs.
Verification

How to check the result

  • Run the operation on a tiny literal input and write the expected type/value before executing it.
  • Inspect the relevant object state before and after the operation, especially when mutable objects are involved.
  • Try one boundary or invalid input and confirm that the returned value or exception matches the intended contract.
Hands-on practice

Demonstrate understanding

Try this:

Build a tiny, inspectable example of While Loops. First evaluate a condition to a truth value. Then execute only the selected indented branch. Write the expected result before running it, and explain one condition that would make the result misleading or invalid.

Use the smallest values that expose the rule. Write the expected value and type first, then compare Python’s actual state/output with that prediction.
Knowledge check

Check reasoning, not memorisation

Before trusting a result from While Loops, which check provides the strongest evidence that you understand and applied it correctly?

Quick reference

Keep the important distinctions visible

Step 1Evaluate a condition to a truth value.
Step 2Execute only the selected indented branch.
Step 3For loops iterate over values from an iterable; while loops repeat while a condition remains true.
Step 4break exits the nearest loop; continue skips to the next iteration.
Lesson summary

What to remember

  • While Loops is part of Python control flow: the rules that decide which statements execute and how many times they execute. Conditions convert program state into True/False decisions, while loops repeat a block until the iteration source is exhausted or a stopping condition is reached.
  • Evaluate a condition to a truth value.
  • Applying the operation to an incompatible type or assuming Python will silently coerce values the way you intended.
  • Run the operation on a tiny literal input and write the expected type/value before executing it.