← Back to the Introduction to Computer Science outline The Course Maker
← Introduction to Computer Science outline
Week 5 · Lecture

Lecture: Loops I: The while Loop

Introduction to Computer Science Free sample edition

Lecture script · about 15–20 minutes spoken · Week 5

Opening

Picture a friend with a step goal of 10000 steps. Each walk around the park adds 2500 steps to her phone's count. She doesn't plan out every walk in advance. She follows one rule: while the count is under the goal, take another walk. After 4 walks the count reads 10000, and she stops.

That one rule is a loop. A receipt program adds one item at a time, and a phone game keeps asking for another try until the right answer comes in. Each of those programs has to repeat, count its passes, and stop at the right moment. When a loop gets that wrong, it runs one step too far, or it never stops at all.

In Week 1 you learned to predict what a line prints and then run it. Week 2 showed that a name can be reassigned, so days can become the old days plus 1. Week 3 read typed input. And Week 4 taught the comparison operators, True and False, and the if statement, which runs its block once. This week the if statement's cousin arrives: a statement that keeps coming back.

Here's the plan for this lecture. We'll write a while loop for the reading log and see why it stops past its goal. Then we'll count with a loop, catch the off-by-one error, stop a runaway loop, and leave a loop with break. After that, Week 6, Loops II, brings the for loop.

1. Repeat with while

Think about a cook adding salt to a pot. The rule is: taste it, and while it's still bland, add a pinch and taste again. The cook never decides in advance how many pinches. The test decides, one pinch at a time.

Python writes that rule as a while loop, a statement that repeats its indented body for as long as its condition is True, checking that condition once at the top of every pass and never in the middle of one. Three more words name its parts. The loop condition is the Boolean expression written after the keyword while; Python tests it before each pass and stops repeating the first time it comes out False. The loop body is the indented lines under a while line, which Python runs from top to bottom on every pass before it returns to test the condition again. And a pass is one complete run through a loop's body, from its first indented line to its last.

Here's the reading log. It starts with 45 pages read, a goal of 300 pages, and days set to 0. The loop line says: while pages read is less than goal. The body has two lines. Pages read gets pages read plus 30, and days gets days plus 1. After the loop, the program prints days and then pages read.

Let's walk it. The first test asks whether 45 is less than 300. It is, so the body runs: pages read becomes 75, and days becomes 1. Then Python goes back up to the while line and tests again, one day at a time, until the test comes out False. Then it skips the body and moves on to the two print lines.

The run prints 9, and then 315. Why 9 days? The pages still needed are 300 minus 45, which is 255. At 30 pages a day, 255 divided by 30 is 8.5. Eight days fall short, so a ninth day is needed.

Pause and try this. The step-counter loop runs while steps is less than 10000, and each walk adds 2500. When the count reaches 10000, does the body run one more time?

Say the test out loud with 10000 in it.

Here's the answer. No. The test asks whether 10000 is less than 10000, which is False, so the loop stops after 4 walks, exactly on the goal.

A while line is an if line that keeps coming back.

2. Check at the top only

A bus driver checks the clock only when the bus pulls into a stop. If the shift ends while the bus is between stops, the driver still drives on to the next stop before checking again. A while loop checks its condition the same way: at one spot only, the top of each pass.

That's why the reading log printed 315 instead of 300. Nothing went wrong. The loop did exactly what you wrote. Let's follow the last two passes. After 8 passes, the total is 45 plus 8 times 30, which is 285. Python goes to the top and asks whether 285 is less than 300. It is, so the ninth pass runs, and it adds a full 30 pages: 285 plus 30 is 315. Back at the top, Python asks whether 315 is less than 300. That's False, so the loop ends. The log finishes 315 minus 300, which is 15 pages past the goal.

Here's a smaller loop that makes the same point. Count starts at 3. The loop runs while count is less than 5. The body adds 1 to count and then prints count. On the first pass, the test asks whether 3 is less than 5. It is, so count becomes 4, and 4 prints. On the second pass, the test asks whether 4 is less than 5. It is, so count becomes 5, and 5 prints. Only then does Python return to the top, ask whether 5 is less than 5, get False, and stop.

So the run prints 4, then 5. That 5 printed even though 5 is not less than 5. The test had already been passed at the top of that pass, and once a pass starts, every line in the body runs.

Pause and try this. Someone says the reading log should stop at 300, because the moment pages read stops being less than 300, the loop quits. Using the pass that starts at 285, explain where that reasoning goes wrong.

Think about when the test actually runs.

Here's the answer. At 285 the test is True, so the whole ninth pass runs and adds 30, reaching 315. The loop never tests in the middle of a pass, so it can't stop at 300.

The test runs at the top of each pass, never in the middle.

3. Count and total

Picture a cashier ringing up a grocery order. The cashier keeps track of two things: how many items have gone through, and the running total so far. Both start at zero before the first item, and both change with every item. Loops keep those same two kinds of numbers.

A counter is a name that gets a starting value before a loop and goes up by one on every pass, so its value tells you how many passes have run. An accumulator is a name that starts at a value such as 0 before a loop and collects a running total, with each pass adding the current amount to it. The plus-equals sign is a shorthand that adds the value on its right to the name on its left and stores the sum back in that name. So count plus-equals 1 means count gets count plus 1.

Let's add up 1 through 5. Total starts at 0, and a counter n starts at 1. The loop runs while n is less than or equal to 5. In the body, total plus-equals n, and then n plus-equals 1. On each pass, total picks up the current n: first 1, then 3, then 6, then 10, then 15. After the loop, the program prints 15, because 1 plus 2 plus 3 plus 4 plus 5 is 15. The loop made 5 passes.

Now here's the habit this course asks for. For every loop, predict three things: what it prints, how many passes it makes, and where its counter ends. Take the pinned counter program. Count starts at 1. The loop runs while count is less than or equal to 5, and the body adds 1 to count. After the loop, it prints count. Count passes the test at 1, 2, 3, 4, and 5, so the loop makes 5 passes. On the pass where count is 5, the test is still True, so count becomes 6. Then 6 fails the test, and the program prints 6.

Pause and try this. In the sum loop, n runs while it's less than or equal to 5. When the loop ends, is n equal to 5 or 6, and why?

Ask which value of n made the test come out False.

Here's the answer. It's 6. The loop can only stop by failing its test, and 5 passes the test, so the body runs once more and n becomes 6, the first value that fails.

Start it before the loop, change it inside, and read it after.

4. Choose less than, or less than or equal to

Imagine a doorman letting guests into a room for 5 people. Does the fifth guest get in? If the rule is "fewer than 5," the fifth guest waits outside. If the rule is "up to 5," the fifth guest walks in. One word changes the count by one. In a loop, one character does the same.

An off-by-one error is a logic mistake in which a loop runs one pass too many or one pass too few, most often because a condition uses less than where it needed less than or equal to, or the reverse.

Here are two loops, one character apart. Both start with count at 1, print count, and add 1. The first runs while count is less than 5. It prints 1, 2, 3, and 4, four lines from four passes, and afterward count is 5. The second runs while count is less than or equal to 5. It prints 1, 2, 3, 4, and 5, five lines from five passes, and afterward count is 6. The only difference is what happens when count equals 5. Less than 5 says no. Less than or equal to 5 says yes.

The same slip shows up in a microwave countdown that should display 3, 2, 1 and then Ready. If its loop runs while seconds is greater than 1 instead of greater than 0, the test fails when seconds reaches 1, and the run displays only 3, 2, Ready. No error message warns you; only a careful trace catches it.

Pause and try this. A loop starts with count at 1, runs while count is less than 5, and prints count on each pass. A classmate expects five lines. How many lines does the body print, and which value is missing?

Test the edge: what happens when count equals 5?

Here's the answer. The body prints 4 lines, 1 through 4, and 5 is missing. When count is 5, the test asks whether 5 is less than 5, which is False, so that pass never runs.

Test the edge: does the body run when the counter equals the limit?

5. Stop a runaway loop

You've probably seen a dog chase its own tail. It never catches it, because every step it takes moves the tail too. A loop can be stuck the same way. The body runs, but nothing it does moves the condition toward False.

An infinite loop is a loop whose condition never becomes False because nothing in its body moves it toward the stop, so the program keeps running until someone stops it by hand.

Here's one, written by mistake. Count starts at 1. The loop runs while count is less than or equal to 5. The body prints count, and that's all. Run it, and it prints 1, then 1 again, then 1 again, and it never stops on its own. Count starts at 1, and nothing in the body changes it, so the test is True on every pass. The computer is not broken. It's doing exactly what you wrote, over and over.

To stop it, you press Ctrl+C, the key press that interrupts a running program in a terminal, the usual way to stop an infinite loop; browser editors offer a Stop button that does the same job. Then you fix the loop. The cure is the update line the body forgot: count plus-equals 1. With that line back, each pass moves count one step closer to 6, and the loop prints 1 through 5 and ends.

Pause and try this. A program has been running for a long time, printing the same line again and again. A classmate decides the website is broken. What's a better first guess, and what's the first thing to do?

Think about what the computer is actually doing.

Here's the answer. It's most likely an infinite loop, a body that never moves its condition toward False. Stop it with Ctrl+C or the Stop button, then find the line that should change the counter.

Every loop needs a line that moves it toward the stop.

6. Leave from the middle with break

Picture someone searching a drawer for a key. They don't know how many things they'll pick up first. The rule is: keep picking things up, and the moment you find the key, stop. That stopping test sits in the middle of the search, not at the start.

Python writes that rule with two pieces. break is the keyword that ends the loop it sits in at once, skipping the rest of the body, so Python carries on with the first line after the loop. And while True is a loop header whose condition can never turn False on its own, used on purpose when a break inside the body decides when the repeating stops.

Here's the pinned program. It looks for the first whole number whose square is greater than 50. N starts at 1. The loop says while True. Inside, an if line asks whether n times n is greater than 50. If it is, the program prints n and breaks. If not, n goes up by 1. When n is 7, the test checks 7 times 7, which is 49, and 49 is not greater than 50, so n becomes 8. On the next pass, it checks 8 times 8, which is 64. That's greater than 50, so the program prints 8 and break ends the loop.

Python also has a related keyword, continue, which skips to the next pass instead of leaving the loop. It comes later in the course; for now you only need its name.

Now the chatbot. Suppose you ask one what the pinned counter program prints, and it answers 5, explaining that the loop counts up to 5. That sounds reasonable. But a chatbot predicts likely text; it doesn't run your program. So you type the four lines into your browser runner and run them, and the output is 6. The chatbot reported the last value that passed the test instead of the first value that failed it, and you caught it with a run.

Pause and try this. The first-square program uses while True. Someone says while True is always a bug. Using the value where this loop stops, explain why it isn't one here.

Look for the break, and the value that reaches it.

Here's the answer. The body holds a break the program is sure to reach. When n is 8, the test 8 times 8 equals 64 is greater than 50, so the program prints 8 and breaks out of the loop.

While True needs a break you are sure to reach.

Closing

Let me pull it together in the order we built it. A while loop repeats its body while its condition is True, so the reading log prints 9 days. The test runs only at the top of each pass, so the log carries its total from 285 to 315. The counter of the pinned program ends at 6, one past the last value that passed. Less than and less than or equal to differ on one value, so test the edge. A loop with no update runs forever; stop it with Ctrl+C, then add the missing line. And while True is safe when a break is sure to be reached, as it is at 8.

Next in this module come the slide deck, the Readings and Resources page, the lecture tutorial, the practice set, the quiz, and the Coding Lab. Then, in Week 6, Loops II, the for loop and range count the passes for you, and loops start to sit inside other loops.


Built with The Course Maker · samples.thecoursemaker.com