while, for and range

while waits on a condition you must change. for walks a tray you have. range(n) is n turns from 0. A running total is every batch job in miniature.

Washing machine cycles

Loops repeat a block of work.

You will be able to

  • Use for to walk a list
  • Use range(n) for a counter
  • Use while only when you change the condition

Three loops

for amt in bills walks a tray you have. range(n) is n turns 0..n-1 (this sandbox). On a laptop range(start, stop, step) exists. while repeats while a condition stays true — you must change that condition or the loop never ends (the sandbox caps it; a laptop will spin).

A running total adds inside and prints once after. range is lazy on a laptop — it does not build a giant list of integers just because you asked for turns.

while vs for

If you have the rows, for is honest. If you need ‘ten retries’, range. If you wait until a reading crosses a threshold, while — plus a maximum count in production so a stuck sensor cannot hang the night job.

Words that matter

for
Visit each item in a list (or each character).
range(n)
n turns from 0 to n − 1 in this sandbox.
while
Repeat while a condition stays true.

Common mistakes

Avoid: Printing inside the loop when accounts asked for one daily total.

Do this: Add inside; print after.

Run it step by step

Each box is a real program. Press Run, change a number, Run again — the output must follow your code.

1. Step 1 — walk a list

Total printed once.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

2. Step 2 — range counter and a while

Three attempts; then a while that counts down.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Example program — Running total

Same shape as a batch job.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Sum of three fees

fees = [10, 25, 50]. Print one total so 85 appears.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. range(4) gives how many turns?
2. A while loop must…

Progress is stored in a browser cookie on this device.