Loops with while

Concepts covered: Conditional Loops

A for loop knows how many passes it will make before it starts: 1 per item. A while loop does not. It checks a condition, runs the body if the condition is True, then returns to the condition and checks again. It stops the first time the check comes back False, and the number of passes is whatever that takes.

count = 0

while count < 5:
    print("Count is", count)
    count = count + 1

print("Loop finished!")
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop finished!
Checkcount < 5Body printscount after the body
10 < 5 is TrueCount is 01
21 < 5 is TrueCount is 12
32 < 5 is TrueCount is 23
43 < 5 is TrueCount is 34
54 < 5 is TrueCount is 45
65 < 5 is Falsenothing, loop ends5

The check runs 6 times and the body runs 5 times. On the sixth check count is 5, 5 < 5 is False, and Python jumps to the line after the loop. A while loop that ends because its condition fails has this shape: the condition is tested 1 more time than the body runs, and the final test is the one that fails. A break statement can end a loop before its condition ever fails.

Setup, condition and progress in a while loop

The progress line is the one that gets dropped. Without count = count + 1, count stays 0, 0 < 5 stays True, and the loop prints "Count is 0" without end. A program stuck like this never reaches the line after the loop, and the only way to stop it is to stop the program from outside.

count = 0
while count < 5:
    print("Count is", count)

print("Loop finished!")

When the number of passes is unknown

A while loop is the better fit when the stopping point depends on the values, which a range cannot know in advance. How many times must 1 be doubled before it passes 100? The loop can find out by doubling until the condition fails.

amount = 1
doublings = 0
while amount < 100:
    amount = amount * 2
    doublings = doublings + 1
print(doublings, "doublings reach", amount)

Output:

7 doublings reach 128

The amounts go 1, 2, 4, 8, 16, 32, 64, 128. The loop doubles 7 times, and the check 128 < 100 is the one that fails. The final amount is 128, past the target: the body runs in full on the pass that crosses 100, and only the next check stops the loop. A while loop can overshoot its target by up to 1 pass's worth of change: here the last pass moved from 64 to 128, and 128 lands 28 past 100.

Zero passes

Because the check comes before the body, a while loop whose condition is False at the start runs its body 0 times. Nothing inside it prints, and every variable keeps the value it had before the while line.

n = 10
while n < 5:
    print("inside")
    n = n + 1
print("n is", n)

Output:

n is 10
Reach for for
  • You have a list or a string to walk through.
  • You know the number of passes up front, so range(n) fits.
  • Python moves to the next item for you, so there is no progress line to forget.
Reach for while
  • The stopping point depends on values computed during the loop.
  • You repeat until a target is reached, such as doubling past 100.
  • You write the progress line yourself, and the loop runs until your condition fails.

What does this program print?

x = 1
while x < 20:
    x = x * 3
print(x)

The comparison on the while line decides the last value the body sees. while n > 0 lets the body run for 1 and stops when n is 0. while n >= 0 also lets 0 through, so the body runs 1 extra time. When a loop prints 1 value too many or too few, test the boundary value against the condition by hand.

A target such as "the first value that is at least X" turns into a condition by asking when the loop should keep going: while the value is still short of X. To find the first multiple of 3 that is at least 20, start from m = 0, loop while m < 20: with m = m + 3 as the progress line, and the loop stops on 21.

About this lesson

This section is part of the Loops: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.