Skip to content
Study Hall
Lesson 3 of 5Computer Programming
Unit 5 · Lesson 3 of 5

Loops: while and for

Repeating work without repeating code — counters, accumulators, and how not to write an infinite loop.

3 min read10 practice questionsAsk AI about this →

Key things to remember

  1. 1Use for when the number of repetitions is known; while when waiting for a condition.
  2. 2range(n) gives 0 to n−1 — n values. range(a, b) stops before b.
  3. 3Every while loop needs initialize, test, and update.
  4. 4Initialize counters and accumulators BEFORE the loop, never inside it.
  5. 5A nested loop runs the inner loop fully for every pass of the outer loop.
  6. 6break leaves the loop; continue skips to the next pass.

Iteration is what makes programs worth writing. A loop lets ten lines of code process ten values or ten million, with no change. Python has two kinds, and choosing the right one removes most loop bugs before you write them: use for when you know how many times, and while when you are waiting for a condition.

The for loop

PythonValues of i
for i in range(5):0, 1, 2, 3, 4 — five values, starting at 0
for i in range(1, 6):1, 2, 3, 4, 5 — stops BEFORE 6
for i in range(0, 20, 5):0, 5, 10, 15 — step of 5
for i in range(10, 0, -1):10, 9, 8 … 1 — counting down
for mark in marks:Each item of the list marks in turn
range() stops BEFORE the end value
range(1, 6) gives 1, 2, 3, 4, 5 — not 6. This half-open convention means range(n) gives exactly n values and range(len(items)) gives exactly the valid indexes. It is also the single most common source of off-by-one errors, so whenever a loop runs one time too few, check this first.

The while loop

PythonWhat it does
count = 0Initialize BEFORE the loop — forget this and the first test fails
while count < 5:Test the condition before every pass
print(count)The body
count = count + 1Update the variable in the condition — forget this and the loop never ends
Every while loop needs three things
Initialize the control variable before the loop. Test it in the condition. Change it inside the body, in a way that moves toward the condition becoming false. Miss any one of the three and you get either a loop that never runs or a loop that never stops.
Tracing by hand is how you find a logic error the computer will not report.total = 0i = 1while i <= 4: total = total + i i = i + 1itotalpasscondition—00—1111 ≤ 4 true2322 ≤ 4 true3633 ≤ 4 true41044 ≤ 4 true51055 ≤ 4 FALSE — exitFinal total = 10One row per pass.Write down everyvariable, every time.Forget the i = i + 1 line andthe table never ends: infinite loop.
Fig 1Tracing a loop by hand: one row per pass, every variable written down.

Counters and accumulators

Two patterns cover most loop work. A counter starts at 0 and increases by 1 whenever something of interest happens — it answers "how many". An accumulator starts at 0 and adds a value each pass — it answers "what is the total". Both must be initialized before the loop, never inside it: putting total = 0 inside the body resets it every pass, and the final answer ends up being just the last value.

PythonWhat it does
total = 0Accumulator, initialized OUTSIDE the loop
count = 0Counter, also outside
for mark in marks:Visit each mark
total = total + markAccumulate the sum
if mark >= 50:Test each one
count = count + 1Count the passes
average = total / len(marks)Use the results after the loop finishes
Indentation decides when something runs
A print indented inside the loop runs every pass. The same print at the outer level runs once, after the loop. "My program prints the total ten times" is almost always a line indented one level too far.

Nested loops

A loop inside a loop runs the inner loop completely for every single pass of the outer loop. Two nested loops of ten passes each means one hundred passes of the inner body — which is how a nested loop can be slow without looking slow. They are the natural fit for grids and tables: the outer loop walks the rows and the inner loop walks the columns within each row.

PythonWhat it does
for row in range(1, 4):Runs 3 times: row = 1, 2, 3
for col in range(1, 4):Runs 3 times for EACH row — 9 passes total
print(row * col, end=" ")Prints one cell, staying on the same line
print()Outside the inner loop: ends the row
A 3×3 times table. The bare print() is indented with the inner loop's header, not its body.
break and continue
break exits the loop immediately, which is how you stop searching once you have found what you wanted. continue skips the rest of the current pass and starts the next one. Both are useful, but a loop with several breaks scattered through it becomes hard to reason about — prefer a clear condition where you can.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Write a loop that adds the whole numbers from 1 to 100 and prints the total.
Example 2
Trace this loop and give the final value of total: total = 0, i = 1, while i <= 5: total = total + i * i, i = i + 1.
Example 3
A student writes: count = 0, while count < 10:, print(count). The program prints 0 forever. Explain and fix.

Where marks get lost

  • Using range(1, 100) when you need 1 to 100 — it stops at 99.
  • Forgetting to update the control variable in a while loop, producing an infinite loop.
  • Initializing an accumulator inside the loop, which resets it every pass.
  • Indenting the final print inside the loop, so it runs every pass instead of once at the end.
  • Using while when the count is known — for handles initialization and updating for you.
  • Forgetting that a nested loop multiplies the work, not adds to it.

Flashcards 9

What values does range(5) produce?
What values does range(2, 10, 3) produce?
The three requirements of a while loop
When should you use for rather than while?
+ 5 more

Practice

1
How many times does the body of for i in range(3, 12): execute?
times
2
What is the final value of total after: total = 0 then for i in range(1, 5): total = total + i?
3
A while loop prints the same value forever. What is the most likely cause?
4
Which loop correctly counts down from 10 to 1?
5
How many times does the innermost line run in: for i in range(4): for j in range(5): print(i, j)?
times
6
Where must an accumulator be initialized?
7
Which keyword exits a loop immediately?
8
Order the parts of a correct while loop.
  1. 1Test the condition
  2. 2Update the control variable
  3. 3Execute the loop body
  4. 4Initialize the control variable
9
A loop is meant to print a total once at the end but prints it on every pass. What is wrong?
10
After n = 1 and while n < 50: n = n * 3, what is the final value of n?

Spot a mistake on this page? Let us know