Python tutorials · Part 6 of 8

The Python while loop

A while loop repeats a block of code for as long as a condition stays true. It's the loop to use when you don't know in advance how many times you'll need to repeat.

A while loop keeps running its block of code as long as a condition is True. Before every pass, Python checks the condition; the moment it's False, the loop stops and the program carries on below it.

Use it when the number of repetitions depends on something that happens while the program runs: until the user types a valid answer, until a balance reaches a target, until an algorithm stops improving.

While loop syntax

count = 1

while count <= 3:
    print("Pass", count)
    count = count + 1

print("Done")
Pass 1
Pass 2
Pass 3
Done

The structure is:

  • while, followed by a condition, any expression that evaluates to true or false, and a colon.
  • An indented body that runs each time the condition is true.
  • Something inside the body that eventually makes the condition false. Here it's count = count + 1.

Step through it: count starts at 1, so 1 <= 3 is true and the body runs. Then 2, then 3. After the third pass count is 4, 4 <= 3 is false, and Python jumps to print("Done").

If the condition is false the very first time, the body never runs at all:

n = 10
while n < 5:
    print("never printed")
print("Skipped the loop")
Skipped the loop

Counting until a goal is reached

The classic while problem: you know the goal, not the number of steps. How many years until savings of 10,000 double at 7% interest?

balance = 10_000
years = 0

while balance < 20_000:
    balance = balance * 1.07
    years += 1

print(years, round(balance, 2))
11 21048.52

You couldn't easily write that as a for loop, because you don't know the 11 in advance. That's the signal to use while. (years += 1 is shorthand for years = years + 1.)

Infinite loops, and how to avoid them

If nothing in the body ever makes the condition false, the loop never ends:

count = 1
while count <= 3:
    print(count)        # forgot to increase count: prints 1 forever

This is an infinite loop. In a terminal, stop it with Ctrl+C; in Jupyter or Colab, press the stop button or interrupt the kernel. To avoid it, check before you run: what changes inside this loop, and will that change make the condition false?

A useful safety net while you're developing is a maximum number of passes:

attempts = 0
value = 1.0

while value > 0.001 and attempts < 100:
    value = value / 2
    attempts += 1

print(attempts, value)
10 0.0009765625

while True with break

Sometimes the natural place to decide "stop" is in the middle of the body, not at the top. The idiom is while True: with a break:

readings = [12, 15, -1, 20]
i = 0
total = 0

while True:
    r = readings[i]
    if r < 0:          # -1 marks the end of the data
        break
    total += r
    i += 1

print(total)
27

break exits the loop immediately. Its partner continue skips the rest of the current pass and goes back to the condition. Both are covered in detail in break, continue and else on loops.

Validating input

while True is the standard pattern for asking until the answer is valid:

while True:
    answer = input("Enter your age: ")
    if answer.isdigit():
        age = int(answer)
        break
    print("Please type a whole number.")

The loop only exits once a valid number arrives, so the code after it can trust age.

while vs for: which should you use?

  • Use for when you're going through a collection or a known number of steps: every item in a list, every line in a file, range(10).
  • Use while when you repeat until something happens and can't say in advance how many times that will be.

If you find yourself writing a while loop with a counter that runs from 0 to a fixed number, a for loop over range() is shorter and can't accidentally loop forever:

for i in range(3):
    print("Pass", i + 1)
Pass 1
Pass 2
Pass 3

Common mistakes

  • Forgetting to update the variable in the condition, which gives an infinite loop.
  • Off-by-one conditions. while count < 3 runs one fewer time than while count <= 3. Trace the first and last pass by hand.
  • Updating in the wrong place. If continue skips past the line that increments your counter, the loop can get stuck.
  • Comparing floats for exact equality. while x != 1.0 may never stop because of rounding; use <, > or a tolerance instead.
  • Using while where for is clearer. Counted loops belong in for.

Practice

  1. Print the powers of 2 that are less than 100.
  2. Starting from n = 27, repeatedly apply: if n is even, halve it; otherwise set it to 3 * n + 1. Count the steps until n reaches 1.
  3. Sum numbers from the list [5, 8, 3, 0, 9] until you hit a 0.

Answers

p = 1
while p < 100:
    print(p, end=" ")
    p *= 2
print()

n, steps = 27, 0
while n != 1:
    n = n // 2 if n % 2 == 0 else 3 * n + 1
    steps += 1
print(steps)

nums, i, total = [5, 8, 3, 0, 9], 0, 0
while nums[i] != 0:
    total += nums[i]
    i += 1
print(total)
1 2 4 8 16 32 64 
111
16

Where this shows up in machine learning

Many training procedures are while loops at heart: keep updating the model until the loss stops improving. That's the idea behind early stopping, which halts training once validation error hasn't improved for a set number of epochs. Optimisers such as gradient descent run until a convergence condition is met or a maximum number of iterations is reached; scikit-learn's max_iter and tol parameters are exactly the condition and the safety net from this tutorial.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.