liveBook · Manning

Off-by-one error

As explained in Software Design for Python Programmers

An off-by-one error is a computational error in which a value or operation count is exactly one greater or one less than intended.

An off-by-one error produces a value one greater or one less than intended, or performs an operation one time too many or too few. Loop bounds and zero-based indexing are common sources. section 6.1.1 section 6.1

Loop and date examples

A loop using while i <= 10 executes six times when i starts at 5. A Date class that accepts month 2 but indexes ('JAN', 'FEB', ...) directly prints MAR instead of FEB. Subtracting one during indexing, or adding a dummy first element, aligns the public month value with the zero-based sequence. section 6.1.1 section 6.1.1

Listing 6.1 (Program 6.1 SurpriseLoop): main.py
if __name__ == '__main__':
    count = 0
    i = 5

    while i <= 10:    #1
        count += 1
        print(f'{count = }, {i = }')
        i += 1

Inspect the loop’s initial value, condition, increment, and printed count to verify its exact execution count. section 6.1.1

How Software Design for Python Programmers covers it

How deep it goes
Explains loop bounds and zero-based indexing through worked examples, then stops at two simple corrective designs.
Examples
Uses a six-iteration while loop and a Python Date class whose month lookup initially prints MAR for February.
What it assumes
Assumes basic Python loops, classes, and sequence indexing while demonstrating zero-based indexing through examples.
What you can do after
Diagnose incorrect counts or values by checking loop boundaries and translating human-facing values before zero-based indexing.
How it connects
Connects zero-based indexing, loops, runtime logic errors, and the Principle of Least Astonishment.

Also explained in

Compare how 4 books explain off-by-one error →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.