SchoolWhool
Quizzes and saved progress, freeSign in freeSign in

Python 2.2Free video11 minLesson 2 of 4 in Module 2

while Loops

Repeat until a condition changes, and avoid infinite loops.

Free sample. Everything in this module opens with a free account.

Watch or read the lesson: while Loops

01Iteration with an unknown number of repetitions

In the previous lesson you learned how to make decisions in Python with if, elif and else. Each of those statements makes its decision once. But what if you need Python to keep checking a condition, and keep repeating the same block of code until something changes?

Here is an example. Imagine you deposit $1,000 into a savings account, and the bank pays 5 percent interest every year. How many years will it take for that $1,000 to grow to at least $2,000?

To keep things simple, assume three things: the interest rate stays the same, the interest is added once a year, and you do not deposit or withdraw any other money.

Why exponentiation is not enough

In the operators lesson you calculated compound interest with exponentiation. If you wanted the balance after ten years, you could write this expression, and Python would calculate it for you:

round(1000 * 1.05 ** 10, 2)
1628.89

This time there is a difference. You do not know how many years to calculate for. The number of years is exactly what you are trying to find, so you cannot put it into the expression in advance.

So instead of choosing a number of years first, calculate the balance one year at a time. Add one year of interest. Check whether the balance has reached $2,000. If it has not, do it again, and again, until you reach the target.

That is exactly the kind of problem loops are designed to solve. A loopKey termCode that runs its body again and again: a while statement or a for statement, with its block. is a statement that runs a block of code repeatedly, and in Python one way to write one is with a while loop.

02The while loop: condition, body and iteration

First, you need two variables: one to store the current balance, and another to keep track of how many years have passed. So the program starts with balance = 1000.0 and years = 0.

You want to keep calculating interest for as long as the balance is below $2,000. So you write while balance < 2000:.

Notice the structure: the while keyword, then a condition, then a colon. It is very similar to the way you wrote if statements in the previous lesson, and just like an if statement, the code underneath it must be indented.

What is different from if

There is one big difference. With an if statement, Python checks the condition and runs the block once. With a while loop, Python keeps coming back to the condition again and again, and as long as the condition is True, the block keeps running.

Now add the code inside the loop. First, increase the balance by 5 percent with balance *= 1.05. This is a shorter way of writing balance = balance * 1.05, the augmented assignment you met in the operators lesson. Then increase the number of years by one with years += 1. Here is the whole program:

balance = 1000.0
years = 0
while balance < 2000:
    balance *= 1.05
    years += 1

That is the loop: just two statements inside it. Running this cell shows nothing, because nothing in it prints a value. The work happens in the variables, and you will look at them in the next part.

The loop body and an iteration

The indented section under the while line is called the loop bodyKey termThe indented block that repeats.. Every time Python executes that body once, from top to bottom, is called an iterationKey termOne run of the loop body..

03Tracing a while loop iteration by iteration

Here is exactly what happens when the loop runs.

Python starts by checking the condition: is the balance less than $2,000? The balance is $1,000, so the answer is True. Python enters the loop and executes the first statement, and the balance increases by 5 percent, to $1,050. Then it increases years by one, so years becomes 1.

Now the important part. Python does not simply continue to the next line after the loop. Instead, it goes back to the while condition and checks it again. But this time the balance is not $1,000 anymore. It is $1,050. So Python checks whether $1,050 is less than $2,000, and it is, so the loop runs again. Another 5 percent of interest is added, the balance becomes $1,102.50, and years becomes 2. Then Python checks the condition again, and the process continues.

Notice that you did not have to write the same calculation over and over. You wrote it once, and Python keeps executing it with the updated values. That is the power of a loop.

The balance year by year

To see how the balance changes over time, you can track each iteration in a table: one column for the year, and another for the balance. Here is the same loop with one print added at the end of the body, so that every iteration prints one row. The balance is displayed with two decimal places, using the .2f format from the formatting lesson, so it is easier to read. That is just formatting: it changes what is displayed, not the value stored in balance.

balance = 1000.0
years = 0
while balance < 2000:
    balance *= 1.05
    years += 1
    print(years, f"{balance:.2f}")
1 1050.00
2 1102.50
3 1157.62
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89
11 1710.34
12 1795.86
13 1885.65
14 1979.93
15 2078.93

After 10 years, the balance is about $1,628.89. That is the same result you calculated with exponentiation at the start of this lesson. But it is still below $2,000, so the loop continues.

Where the loop stops

After 14 years, the balance is about $1,979.93. That is very close, but not quite there. Because the balance is still less than $2,000, Python runs the loop one more time, and after year 15 the balance reaches about $2,078.93.

Now Python goes back to the condition. Is the balance still less than $2,000? No. The condition is False, so the loop stops, and the value of years is 15. You can check both variables after the loop has finished:

years, round(balance, 2)
(15, 2078.93)

So here is the answer: it takes 15 years for the balance to reach at least $2,000, under the assumptions made at the start.

Notice that the final balance is a little higher than $2,000, and that is completely fine. The goal was never to reach exactly $2,000. It was to find out when the balance would reach or exceed that amount, and that happened in year 15.

04Iteration count: zero iterations, and when the condition is evaluated

Now change the example slightly. Suppose you start with $2,500 instead of $1,000, and reset years to zero. Here is the same loop, with print(years) after it:

balance = 2500.0
years = 0
while balance < 2000:
    balance *= 1.05
    years += 1
print(years)
Predict first

What do you think happens when you run it? How many times will the loop body execute? Think about the first condition check. Think it through before reading on.

I have a guess. Show meHide the answer
0

The answer is zero. The loop does not run at all, because the very first condition check is False. The balance is $2,500, and $2,500 is not less than $2,000. So Python skips the loop body completely, and years stays at 0.

That is something important to remember about while loops. A while loop can run many times, it can run once, or it can run zero times. It all depends on the condition.

When Python checks the condition

Here is another example, which shows exactly when Python checks the condition. Start with a variable called count, set to 10. Then write a loop that runs while count is greater than zero. Inside the loop, print count, and then subtract 3 from it with count -= 3. The last line of the cell is count on its own, so the notebook shows the value left in the variable after the loop:

count = 10
while count > 0:
    print(count)
    count -= 3
count
Predict first

What will the value of count be after the loop finishes? This is not a question about which numbers get printed. It is about what value is actually left in the variable. Trace the updates one at a time before you make a prediction. Think it through before reading on.

I have a guess. Show meHide the answer
10
7
4
1
-2

Trace it. count starts at 10, which is greater than zero, so Python prints 10 and then subtracts 3. Now count is 7. The condition is still True, so Python prints 7 and subtracts 3 again. Now count is 4, so it prints 4, subtracts 3, and count is 1.

1 is still greater than zero, so the loop runs again. It prints 1 and then subtracts 3, so count becomes -2. Only after that does Python go back and check the condition again. And now the condition is False, because -2 is not greater than zero, so the loop stops.

That means the printed values are 10, 7, 4 and 1, but the final value of count is -2, not 1.

The condition is checked before each iteration

Here is why. Python does not continuously monitor the condition while the loop body is running. It checks the condition before each iteration. Once an iteration begins, the statements in the body run normally, unless something explicitly interrupts that flow. Then Python returns to the condition for the next check. That is why the last subtraction still happened, even though it took count below zero.

05Infinite loops, KeyboardInterrupt, and the termination rule

Go back to the savings example for a moment. Reset balance to 1000.0 and years to 0. Remember, the loop continues while the balance is below $2,000, and inside the loop the balance increases by 5 percent.

But what if you accidentally remove that balance update, so the body has only years += 1?

balance = 1000.0
years = 0
while balance < 2000:
    years += 1
Predict first

What do you think actually happens now? Think it through before reading on.

I have a guess. Show meHide the answer

years keeps increasing: 1, 2, 3, 4, and so on. But the balance never changes. It stays at $1,000, and the condition checks the balance, not the number of years. So every time Python checks whether the balance is less than $2,000, the answer is still True, and the loop keeps running forever, unless something interrupts it.

This is called an infinite loopKey termA loop that never terminates. In 2.2's example, the condition stays True and there is no other exit. A while True loop with a reachable break can terminate (2.4).: a loop whose condition never becomes False. It is one of the most common mistakes beginners make with while loops.

Stopping a running cell

A cell with an infinite loop never finishes, so it stays running. To stop it, click the stop button on the running cell to interrupt execution. When this cell was interrupted, the notebook showed a traceback ending with this line:

KeyboardInterrupt

A KeyboardInterrupt simply means that the execution was interrupted. It is not a bug in Python. Nothing was printed before it, because nothing in the loop prints.

Then you can fix the code and run it again. Here is the cell with the balance update put back, and a print after the loop:

balance = 1000.0
years = 0
while balance < 2000:
    balance *= 1.05
    years += 1
print(years, round(balance, 2))
15 2078.93

The corrected loop finishes, with the same answer as before: 15 years.

The termination rule

Here is a useful habit to develop. Whenever you write a while loop, ask yourself two questions:

  1. What is the condition checking?
  2. What changes inside the loop that will eventually make that condition False?

If nothing changes, or if the value changes in the wrong direction, your loop might never stop. And even if another variable keeps changing, as years did, that does not help unless it affects the condition.

06Recap and challenge: conditions, iteration and termination

To bring everything together:

  • A while loop lets Python repeat a block of code as long as a condition is True. You write the while keyword, a condition and a colon, with an indented body underneath.
  • The indented block is the loop body, and each execution of the body is an iteration.
  • The condition is checked before every iteration, not while the body is running. That is why a while loop can run many times, once, or not at all.
  • An infinite loop happens when the condition never becomes False. Stop a running cell with the stop button, which raises KeyboardInterrupt, then fix the code.
  • For every while loop, ask what the condition checks, and what changes inside the loop to make it False eventually.

Your challenge

Go back to the savings example. This time, change the starting balance to $2,500 and use an annual interest rate of 4 percent. Your goal is to find out how many years it takes for the balance to reach at least $5,000.

There is one extra condition: the loop should stop after 30 years at most, even if the balance has not reached the target.

Think about how you can combine those two conditions. The balance should still be below the target, and the number of years should still be less than 30. Both conditions need to be True for the loop to continue.

In the next lesson, you will look at another kind of loop. Instead of repeating a block based on a condition, you will go through the items in a sequence, one at a time, with the for loop.