Python Loops · Lesson 40 of 149

Python Loop Design and Infinite Loops

What you will learn

  • How to choose between for and while
  • What guarantees that a loop stops, and the usual causes of infinite loops
  • How to avoid off-by-one errors
  • Retry loops with a limit, and early exit
  • How to do less work inside a loop
  • How to test and trace a loop

1. For or while?

Situation Choose Why
go through every item of a collection for no counting, no update to forget
repeat a known number of times for _ in range(n) the count is built in
repeat until something happens, and you do not know when while the condition decides
repeat until the user gives a valid answer while the number of tries is unknown

A good rule: if you can write it as a for loop, do. A for loop cannot forget its update, and cannot run forever over a normal collection.

Quick check: which loop fits "ask until the user types yes"?

A while loop, because you cannot know how many tries it will take.

2. Making sure a loop stops

A loop ends when its test becomes false (or when a break runs). Before you run a while loop, ask yourself three questions:

  1. What changes on each pass?
  2. Does the change move the test towards false?
  3. Can the test actually become false, for every possible input?
def countdown(n):
    while n > 0:
        print(n, end=" ")
        n -= 1
    print("liftoff")

countdown(3)
3 2 1 liftoff

Here n goes down by 1 every pass, the test is n > 0, so it stops after n passes, for any positive start.

Common causes of an infinite loop

Cause Example
no update while n > 0: and nothing changes n
update in the wrong direction n += 1 when the test is n > 0
continue before the update lesson 6.3
a test that can never be false while x != 1.0 with a float
input never changes waiting for a value that is read only once, before the loop

Press Ctrl + C to stop a loop that does not end (lesson 6.1).

The float trap

Floating-point numbers do not add up exactly (lesson 3.4), so never wait for a float to equal a value:

x = 0.0
steps = 0
while x != 1.0 and steps < 15:
    x += 0.1
    steps += 1
print(steps, x, x == 1.0)
15 1.5000000000000002 False

Adding 0.1 ten times gives 0.9999999999999999, never exactly 1.0, so the test never became false. Only the extra check steps < 15 saved the loop. Use < instead of !=, or count with integers:

x = 0.0
steps = 0
while x < 1.0:
    x += 0.1
    steps += 1
print(steps, x)
11 1.0999999999999999

Even this took 11 passes, not 10, because after ten additions x was 0.9999999999999999, still less than 1.0. The cleanest solution is to loop on a whole-number count: for i in range(10): x = i / 10.

3. Safety limits

When a loop depends on something unpredictable, add a maximum. It is a cheap insurance:

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

(This is the Collatz sequence, which is believed, but not proven, to always reach 1. A limit protects you from relying on that.)

Retry loops with a limit

Asking again is a classic while job, but forever is rarely wanted. A for loop over the allowed tries, with break on success and else for giving up (lesson 6.3), says exactly what you mean:

MAX_TRIES = 3
answers = iter(["x", "y", "z", "5"])   # pretend these are typed by a user

for attempt in range(1, MAX_TRIES + 1):
    reply = next(answers)
    if reply.isdigit():
        print("ok on try", attempt)
        break
    print("try", attempt, "failed")
else:
    print("gave up after", MAX_TRIES, "tries")
try 1 failed
try 2 failed
try 3 failed
gave up after 3 tries

In a real program, reply = input("Number: ") replaces the pretend answers.

The "do it at least once" loop

Some languages have a loop that tests after the block (do ... while). Python does not, but while True with break does the same:

attempts = iter(["abc", "12", "7"])
while True:
    value = next(attempts)
    if value.isdigit():
        break
    print("invalid:", value)
print("accepted", value)
invalid: abc
accepted 12

The block runs once before the first check. This avoids repeating the input line before and inside the loop (lesson 6.1).

4. Off-by-one errors

The most common loop bug is being one too many or one too few. Think about the fence-post problem: a fence of 5 sections needs 6 posts. Two habits help:

You want Use
n items, positions 0 to n - 1 range(n) or range(len(items))
pairs of neighbours in n items range(n - 1): there are n - 1 pairs
numbers 1 to n inclusive range(1, n + 1)
items = ["a", "b", "c"]
for i in range(len(items) - 1):
    print(items[i], items[i + 1], end="; ")
print()
a b; b c; 

Three items have two neighbouring pairs, so the loop runs len(items) - 1 times. Going one too far fails:

for i in range(len(items) + 1):
    items[i]
IndexError: list index out of range

When in doubt, try the smallest cases: a list of one item, and a list of none.

5. Do less work in the loop

The block runs again and again, so anything that does not change should be done once, before the loop:

  • Work out n = len(items) before the loop if you use it on every pass.
  • Do not rebuild the same list or text on each pass.
  • Test membership against a set, not a list: x in allowed_set is much faster for big collections than x in allowed_list, because a list is searched item by item (sets are chapter 10).
  • Stop early: use break or return as soon as you have the answer.
def first_negative(nums):
    for n in nums:
        if n < 0:
            return n
    return None

print(first_negative([3, 4, -1, -5]), first_negative([1, 2]))
-1 None

The function leaves at the first negative number, and never looks at the rest. (def and return are chapter 11.)

6. Keeping loops readable

  • Name the loop variable well: for student in students, not for x in y.
  • Keep the block short. If it grows, move part of it into a function (chapter 11).
  • Avoid deep nesting. Use continue to skip unwanted items at the top, and break to stop early, so the main work is not indented three levels (lesson 6.3).
  • Prefer for with enumerate and zip over counters you manage by hand (lesson 6.6).

7. Testing and tracing a loop

Test the edges. For any loop, check these inputs:

Case Why
an empty collection the loop runs zero times: is the result still sensible?
one item start and end are the same item
the first and last item where off-by-one errors hide
a value that never matches the "not found" path
print(first_negative([]), sum([]), max([], default=None))
None 0 None

Trace by hand. Add a print of the key variables inside the loop to watch what happens (this is "print debugging", lesson 18.1):

n = 3
total = 0
while n > 0:
    total += n
    n -= 1
    print("n =", n, "total =", total)
n = 2 total = 3
n = 1 total = 5
n = 0 total = 6

Remove the print when the loop works.

Worked example: binary search, a loop that must stop

To find a value in a sorted list, look at the middle, and discard the half that cannot contain it. Repeat until found or nothing is left.

def binary_search(sorted_list, target):
    low = 0
    high = len(sorted_list) - 1
    while low <= high:
        mid = (low + high) // 2
        if sorted_list[mid] == target:
            return mid
        elif sorted_list[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

data = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(binary_search(data, 23), binary_search(data, 5))
print(binary_search(data, 7), binary_search([], 1), binary_search([4], 4))
5 1
-1 -1 0
Question Answer
What changes each pass? low goes up or high goes down, so the range shrinks
Does it move towards the end? yes: the range loses at least one position each time
Can the test become false? yes: low > high when nothing is left
Edge cases empty list gives -1; one item works

The data is made up. A loop that halves the range needs at most about log2(n) passes: for a million items, about twenty.

Common mistakes

  • Waiting for a float to equal a value with != or ==.
  • Forgetting that a loop must make progress towards its stopping condition.
  • Off-by-one in range: range(n) stops at n - 1; neighbours need n - 1.
  • Retrying forever with no limit.
  • Repeating work inside the loop that could be done once before it.
  • Testing only the usual case, and not empty or one-item input.

Key takeaways

  • Prefer for when you can; use while when you cannot know the number of passes.
  • Make sure each pass moves the test towards false, and add a safety limit when the input is unpredictable.
  • Never loop until a float equals a value; use < or whole-number counts.
  • Mind the fence posts: n neighbours need n - 1 pairs, and range(1, n + 1) includes n.
  • Do invariant work before the loop, exit early, test empty and one-item input, and trace with print.

Practice

1. What makes this loop infinite? n = 5 then while n > 0: print(n).

Show answer

n is never changed, so n > 0 stays true. Add n -= 1 inside the loop.

2. A list has 6 items. How many neighbouring pairs are there, and which range loops over them?

Show answer

5 pairs. Use range(len(items) - 1).

3. Why is while total != 1.0: with total += 0.1 risky?

Show answer

Float errors mean total may never be exactly 1.0, so the loop may never stop. Use <, a whole-number counter, or a safety limit.

4. Write a retry loop that allows 3 tries to type "yes", and prints denied if all fail.

Show answer
for attempt in range(3):
    if input("Type yes: ") == "yes":
        print("welcome")
        break
else:
    print("denied")

5. Why is x in allowed_set often better than x in allowed_list inside a big loop?

Show answer

A list is searched item by item, which gets slow for large lists. A set finds an item directly, so the test stays fast.

6. Name four inputs you should test a loop with.

Show answer

An empty collection, a single item, the first and last item (the edges), and a value that never matches.