0%

Repeating Work with Loops · practice

Repeat While a Condition Holds

A for visits the values a collection supplies, one at a time. With the fixed and ranges you have used so far, you can count those values in advance.

For other tasks, it is more natural to describe when the work should continue. Keep saving while the balance is below a goal. Keep asking while an answer is unusable. You do not need to work out the number of passes first.

That is what a while loop is for.

The shape of a while loop

Try it

Read it as an English sentence again: “while count is greater than zero, do this.”

Python checks the first. If it is True, it runs the body and comes back to check again. If it is False, it skips the body and continues below the loop. The condition is tested before every pass, including the first one.

The condition is an ordinary comparison, exactly like the ones in an statement. The difference is that if asks once and while keeps asking.

Three parts that must line up

For a loop controlled by a changing number, these three parts need to work together. They are easy to see in the countdown:

count = 3            # 1. set up the variable the condition depends on
while count > 0:     # 2. test it before every pass
    print(count)
    count = count - 1  # 3. change it inside the body

Miss the first part and Python raises a . Miss the third and the condition never becomes False, which is a problem serious enough that the next lesson is about it.

Trace count yourself through the countdown: 3, then 2, then 1, then 0. Python returns to the while line after every pass. When count reaches 0 the condition is False and the loop is done. The exercise at the end of this lesson is a good one to run under Step, where you can watch that return trip happen.

Zero passes is a valid outcome

Because the test comes first, a while loop can run its body no times at all:

Try it

The condition was already False, so Python skipped straight past the body. That behavior is often what you want, and it is worth remembering when a loop mysteriously produces no output.

Choosing between for and while

You can write a countdown either way:

Try it

Both are correct here, so use the one that says what you mean:

UseWhen
forYou are walking through a collection, or repeating a known number of times
whileYou want a condition to decide whether another pass is needed

The savings question is a good example of the second kind. You could work out the number of weeks yourself, but the loop can keep track while it makes the deposits:

Try it

Notice that balance ends at 120, not 100. The loop finished the whole pass that carried it past the goal and only then found the condition False. Changing the balance does not interrupt the body: the condition is checked again when Python returns to the while line.

What does this code print?

number = 1

while number < 20:
    print(number)
    number = number * 3

When does Python check a while condition?

Now write a while loop that tracks the deposits needed to reach a goal.

Task

You are saving 25 each week toward a goal of 150. Write a while that keeps depositing until the balance reaches the goal, then reports how long it took.

Complete the program so that on every pass it:

  • adds deposit to balance;

  • adds 1 to weeks;

  • prints a progress line in the form Week 1: 25.

The loop should keep running while balance is less than goal. Keep the final summary line, which runs once after the loop.

Expected output:

Week 1: 25
Week 2: 50
Week 3: 75
Week 4: 100
Week 5: 125
Week 6: 150
Reached 150 after 6 weeks.

Change deposit to 40 and run it again. The loop should still stop as soon as the goal is reached, even though the balance passes it. Set it back to 25 before you submit.

Watch the condition being tested

Once your loop runs, press Step in the editor toolbar and move through it with Next.

Watch the highlight reach the bottom of the body and jump back up to the while line every time. That return trip is where the gets tested again. Keep an eye on balance in the panel as it approaches 150, and notice that the changed balance is checked when Python returns to the while line.