---
title: "Finding and Fixing Bugs"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 23
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/23-finding-and-fixing-bugs
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 23 — Finding and Fixing Bugs

Leo wrote a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) for the average of his five marks. They are 12, 10, 11, 9 and 11, all between 9 and 12, and his [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints 13.25. Python gave no warning: it did exactly what Leo wrote, which is not what he meant. Every programmer writes [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that go wrong; good programmers have a method for finding out why.

**You already know.**

Python stops with an [error message](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-error) when it cannot carry out a line ([Chapter 14](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#ch-g6-first-python-program)). A [trace table](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-trace-table) follows the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the [variables](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), one row per step ([Chapter 15](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#ch-g6-variables-and-input)). A [function call](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) runs the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function)’s body and comes back with a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) ([Chapter 19](https://one-course.com/books/computer-science/1/en/chapter/19-functions#ch-g7-functions)); a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) has indices from 0 to its length minus 1 ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)).

## 23.1 Three kinds of error

**Definition 23.1 (Bug).**

A *bug* is a mistake in a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that makes it behave differently from what its author meant.

**Definition 23.2 (Syntax error, runtime error, logic error).**

A *syntax error* breaks the rules of the language: Python refuses to start the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) at all. A *runtime error* happens while the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) runs: it starts, then stops at a line that cannot be carried out. A *logic error* lets the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) run to the end, but with a wrong result.

A colon forgotten at the end of a `for` line is a [syntax error](#def-g7-finding-and-fixing-bugs-kinds). Python reads the whole [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) before running anything, so not even the first line runs:

```
$ python missing_colon.py
  File "~/session/missing_colon.py", line 2
    for mark in marks
                     ^
SyntaxError: expected ':'
[exit status 1]
```

***Output 23.1.** A [syntax error](#def-g7-finding-and-fixing-bugs-kinds): the mark under the line points at the place where the colon was expected.*

Dividing by zero is a [runtime error](#def-g7-finding-and-fixing-bugs-kinds): the first two lines run, and the third stops the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program).

```python
total = 53
count = 0
print("average:", total / count)
```

***Listing 23.1.** An average of nothing. code/grade-7/05-finding-and-fixing-bugs/listings/zero_division.py*

```
$ python zero_division.py
Traceback (most recent call last):
  File "~/session/zero_division.py", line 3, in <module>
    print("average:", total / count)
                      ~~~~~~^~~~~~~
ZeroDivisionError: division by zero
[exit status 1]
```

***Output 23.2.** A [runtime error](#def-g7-finding-and-fixing-bugs-kinds).*

Leo’s average is a [logic error](#def-g7-finding-and-fixing-bugs-kinds), the hardest kind: nothing warns, and the wrong answer looks like any other number. Only a person who knows what to expect can see that 13.25 is impossible.

![Three questions tell the three kinds of error apart. “No bug found” is not “no bug”: it only means that this run gave the right answer.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-finding-and-fixing-bugs/fig-23b22ee8bc0b.svg)

*Three questions tell the three kinds of error apart. “No [bug](#def-g7-finding-and-fixing-bugs-bug) found” is not “no [bug](#def-g7-finding-and-fixing-bugs-bug)”: it only means that this run gave the right answer.*

## 23.2 Reading an error report from the bottom

When a [runtime error](#def-g7-finding-and-fixing-bugs-kinds) happens inside a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function), Python reports the whole path that led there.

**Definition 23.3 (Traceback).**

A *traceback* is the error report of a [runtime error](#def-g7-finding-and-fixing-bugs-kinds): it [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) the calls that were under way when the error happened, from the top of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) down to the failing line, and ends with the name of the error.

```python
def average(values):
    total = 0
    for value in values:
        total = total + value
    return total / len(values)


def report(name, values):
    print(name, "average:", average(values))


report("Leo", [12, 10, 11, 9, 11])
report("Mia", [])
```

***Listing 23.2.** An error two calls deep. code/grade-7/05-finding-and-fixing-bugs/listings/two_calls.py*

```
$ python two_calls.py
Leo average: 10.6
Traceback (most recent call last):
  File "~/session/two_calls.py", line 13, in <module>
    report("Mia", [])
  File "~/session/two_calls.py", line 9, in report
    print(name, "average:", average(values))
                            ^^^^^^^^^^^^^^^
  File "~/session/two_calls.py", line 5, in average
    return total / len(values)
           ~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
[exit status 1]
```

***Output 23.3.** Leo’s line is printed; Mia’s call fails.*

Read a [traceback](#def-g7-finding-and-fixing-bugs-traceback) from the bottom. The last line says *what* went wrong: a division by zero. The lines just above say *where*: line 5, in `average`. Going up, each pair of lines is one step back along the path: `average` was called from line 9, in `report`, which was called from line 13, the main [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), with an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list).

![in short: each box is one call under way, the deepest one at the bottom.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-finding-and-fixing-bugs/fig-8ce043524d6d.svg)

*[Output 23.3](#out-g7-finding-and-fixing-bugs-two-calls) in short: each box is one call under way, the deepest one at the bottom.*

## 23.3 Tracing

A [trace table](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-trace-table) by hand ([Chapter 15](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#ch-g6-variables-and-input)) works for a few steps. For more, the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can trace itself: extra `print` lines show the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) as it runs. Here is Leo’s [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function), then the same [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) with tracing lines:

```python
def average(marks):
    total = 0
    for mark in marks:
        total = total + mark
    return total / 4


print(average([12, 10, 11, 9, 11]))
```

***Listing 23.3.** Leo’s average. code/grade-7/05-finding-and-fixing-bugs/listings/average_bug.py*

```
$ python average_bug.py
13.25
```

***Output 23.4.** Higher than every mark.*

```python
def average(marks):
    total = 0
    for mark in marks:
        total = total + mark
        print("  trace: mark", mark, "total", total)
    print("  trace: dividing", total, "by 4")
    return total / 4


print(average([12, 10, 11, 9, 11]))
```

***Listing 23.4.** The same [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function), with two tracing lines. code/grade-7/05-finding-and-fixing-bugs/listings/average_trace.py*

```
$ python average_trace.py
  trace: mark 12 total 12
  trace: mark 10 total 22
  trace: mark 11 total 33
  trace: mark 9 total 42
  trace: mark 11 total 53
  trace: dividing 53 by 4
13.25
```

***Output 23.5.** The trace: the total is right, the division is not.*

The total, 53, is right, so the walk is not to blame. The trace shows the mistake at once: Leo divides by 4, the number of marks he had last week, not by the number of marks in the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). `len(marks)` always counts them:

```python
def average(marks):
    total = 0
    for mark in marks:
        total = total + mark
    return total / len(marks)


print(average([12, 10, 11, 9, 11]))
```

***Listing 23.5.** The average, fixed. code/grade-7/05-finding-and-fixing-bugs/listings/average_fixed.py*

```
$ python average_fixed.py
10.6
```

***Output 23.6.** 10.6, between 9 and 12, as it must be.*

Once the [bug](#def-g7-finding-and-fixing-bugs-bug) is fixed, the tracing lines are removed: they were scaffolding, not part of the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program). Starting them with `" trace:"` makes them easy to find.

## 23.4 The smallest input that shows the bug

**Definition 23.4 (Debugging).**

*Debugging* is finding the cause of a [bug](#def-g7-finding-and-fixing-bugs-bug) and fixing it.

The first step of [debugging](#def-g7-finding-and-fixing-bugs-debugging) is to make the [bug](#def-g7-finding-and-fixing-bugs-bug) happen again, on purpose. The second is to make the [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) as small as possible: a [bug](#def-g7-finding-and-fixing-bugs-bug) seen on a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of a thousand [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is hard to follow, the same [bug](#def-g7-finding-and-fixing-bugs-bug) on a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is easy. This [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) should return the first word of a sentence:

```python
def first_word(sentence):
    end = sentence.find(" ")
    return sentence[:end]


for sentence in ["The fox ran", "Hello there", "Stop", "a"]:
    print("[" + first_word(sentence) + "]")
```

***Listing 23.6.** The first word, with brackets to show where it starts and ends. code/grade-7/05-finding-and-fixing-bugs/listings/first_word_bug.py*

```
$ python first_word_bug.py
[The]
[Hello]
[Sto]
[]
```

***Output 23.7.** Right twice, then wrong twice.*

It fails on `"Stop"`, a sentence of one word, and on `"a"`, the smallest such sentence: one letter, and the answer is empty. With no space, `find` returns $-1$, and `sentence[:-1]` is everything except the last [character](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string). The fix handles the case with no space:

```python
def first_word(sentence):
    end = sentence.find(" ")
    if end == -1:            # no space: the sentence is one word
        return sentence
    return sentence[:end]


for sentence in ["The fox ran", "Hello there", "Stop", "a"]:
    print("[" + first_word(sentence) + "]")
```

***Listing 23.7.** One more case. code/grade-7/05-finding-and-fixing-bugs/listings/first_word_fixed.py*

```
$ python first_word_fixed.py
[The]
[Hello]
[Stop]
[a]
```

***Output 23.8.** All four right.*

Many [bugs](#def-g7-finding-and-fixing-bugs-bug) hide at the edges: an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), the first or the last [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). A fence of $n$ posts has $n - 1$ gaps between them, and counting posts when you mean gaps, or the other way round, is so common that it has a name: an *off-by-one* mistake.

![Five posts, four gaps. A list of n items has n - 1 pairs of neighbours, and its last index is n - 1.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-finding-and-fixing-bugs/fig-ad939b577b87.svg)

*Five posts, four gaps. A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of $n$ [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) has $n - 1$ pairs of neighbours, and its last [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is $n - 1$.*

## 23.5 Changing one thing at a time

**Method 23.5 (Debugging, one step at a time).**

1. **Reproduce** : find an [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) that shows the [bug](#def-g7-finding-and-fixing-bugs-bug) every time.
2. **Shrink** : make that [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) as small as you can.
3. **Guess** : read the error report or a trace, and guess the cause.
4. **Change one thing** , and run again on the same [input](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) .
5. If the [bug](#def-g7-finding-and-fixing-bugs-bug) is gone, keep the change and run the other [inputs](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) too; if not, undo the change and go back to step 3.

Changing two things at once seems faster, but if the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) then works, or fails differently, you cannot tell which change did it.

![The debugging cycle of .](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-finding-and-fixing-bugs/fig-de18b4756564.svg)

*The [debugging](#def-g7-finding-and-fixing-bugs-debugging) cycle of [Method 23.5](#met-g7-finding-and-fixing-bugs-cycle).*

**History — A real bug.**

Engineers already called a fault a “[bug](#def-g7-finding-and-fixing-bugs-bug)” long before [computers](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer). On 9 September 1947, at Harvard, in Cambridge, Massachusetts, the operators of the Mark II, a [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) built from electrical switches called relays, found a moth caught in one of them. They taped it into the machine’s log book with the words “First actual case of [bug](#def-g7-finding-and-fixing-bugs-bug) being found”.

![The log-book page of 9 September 1947, with the moth taped under the time 15:45.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-finding-and-fixing-bugs/img-2e8c663f5ca7.jpg)

*The log-book page of 9 September 1947, with the moth taped under the time 15:45.*

## 23.6 Exercises

**Exercise 23.1 ★.**

Which kind of error is each of these: (a) a missing bracket; (b) a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) past the end; (c) a price total that is 10 times too big; (d) a word spelt `pritn`, on a line that runs; (e) a [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) that counts one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) too few; (f) a `while` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) with `whle`?

**Solution of Exercise 23.1.**

(a) [syntax error](#def-g7-finding-and-fixing-bugs-kinds); (b) [runtime error](#def-g7-finding-and-fixing-bugs-kinds); (c) [logic error](#def-g7-finding-and-fixing-bugs-kinds); (d) [runtime error](#def-g7-finding-and-fixing-bugs-kinds): the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) starts, and stops with a `NameError` when it reaches that line; (e) [logic error](#def-g7-finding-and-fixing-bugs-kinds); (f) [syntax error](#def-g7-finding-and-fixing-bugs-kinds).

**Exercise 23.2 ★.**

Here is a [traceback](#def-g7-finding-and-fixing-bugs-traceback). What went wrong, on which line, and inside which [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function)?

```
$ python last_item.py
Traceback (most recent call last):
  File "~/session/last_item.py", line 5, in <module>
    print(last([4, 8, 15]))
          ^^^^^^^^^^^^^^^^
  File "~/session/last_item.py", line 2, in last
    return values[len(values)]
           ~~~~~~^^^^^^^^^^^^^
IndexError: list index out of range
[exit status 1]
```

***Output 23.9.** An error report to read.*

**Solution of Exercise 23.2.**

From the bottom: an `IndexError`, a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) out of range, on line 2, inside the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `last`, called from line 5. A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of 3 [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) has indices 0 to 2, and `values[len(values)]` asks for [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 3; the last [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is `values[len(values) - 1]`, or `values[-1]`.

**Exercise 23.3 ★.**

In [Output 23.5](#out-g7-finding-and-fixing-bugs-average-trace), which lines come from the tracing lines? What remains once they are removed?

**Solution of Exercise 23.3.**

The six lines that start with `trace:`. Only the last line, 13.25, remains.

**Exercise 23.4 ★.**

Tom’s [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) stops with `SyntaxError: '(' was never closed` on the line `print("count:", len(marks)`. Fix it.

**Solution of Exercise 23.4.**

Each opening bracket needs its closing bracket; `print` opens one and `len` opens another, so two are needed at the end: `print("count:", len(marks))`.

**Exercise 23.5 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should add the first five marks, but prints 67. Why? Fix it.

```python
marks = [12, 10, 11, 9, 11, 14, 8, 13]
total = 0
for i in range(6):
    total = total + marks[i]
print("total of the first five marks:", total)
```

***Listing 23.8.** One mark too many. code/grade-7/05-finding-and-fixing-bugs/exercises/first_five.py*

**Solution of Exercise 23.5.**

`range(6)` gives the indices 0 to 5: six marks, the sixth being 14 ($53 + 14 = 67$). Write `range(5)`, and the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints 53.

**Exercise 23.6 ★★.**

This [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) should count the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) above `limit`; it has a tracing line. It answers 0 for `[3, 9, 7]` and 5. Read the trace and find the [bug](#def-g7-finding-and-fixing-bugs-bug).

```python
def count_above(values, limit):
    count = 0
    for value in values:
        if value > limit:
            count = count + 1
        print("  trace: value", value, "count", count)
        return count


print(count_above([3, 9, 7], 5))
```

***Listing 23.9.** A count with a trace. code/grade-7/05-finding-and-fixing-bugs/listings/count_above_trace.py*

```
$ python count_above_trace.py
  trace: value 3 count 0
0
```

***Output 23.10.** Only one line of trace.*

**Solution of Exercise 23.6.**

The trace has one line only: the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) stopped after its first [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). The `return` is indented inside the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), so the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) returns at the end of the first turn. Moved back to the level of `for`, after the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), it gives 2.

**Exercise 23.7 ★★.**

Add a tracing line to [Listing 23.6](#lst-g7-finding-and-fixing-bugs-first-word-bug) that prints `end` for each sentence. What does it print for `"Stop"`?

**Solution of Exercise 23.7.**

The line `print(" trace: end", end)`, just after `end` is computed, prints 3, 5, $-1$ and $-1$; for `"Stop"` it prints $-1$, which shows that `find` found no space.

**Exercise 23.8 ★★.**

Noor writes `if mark =< 10:`. Which kind of error is it, and how is it written in Python?

**Solution of Exercise 23.8.**

A [syntax error](#def-g7-finding-and-fixing-bugs-kinds): Python reports `invalid syntax` and runs nothing. The [comparison](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) is written `<=`, the `<` first, as it is said: “less than or equal to”.

**Exercise 23.9 ★★.**

This [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) should say whether a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is in order from small to large, equal neighbours allowed. Find the smallest [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) on which it is wrong, then fix it.

```python
def is_sorted(values):
    """True when every item is at least as large as the one before it."""
    for i in range(len(values) - 1):
        if not values[i] < values[i + 1]:
            return False
    return True


print(is_sorted([1, 2, 3]), is_sorted([3, 1]), is_sorted([2, 5, 5, 8]))
```

***Listing 23.10.** In order? code/grade-7/05-finding-and-fixing-bugs/exercises/is_sorted_bug.py*

**Solution of Exercise 23.9.**

`values[i] < values[i + 1]` is false for two equal neighbours, so a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) with equal neighbours is called not in order. The smallest such [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is `[1, 1]`. The [comparison](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) must be `<=`:

```python
def is_sorted(values):
    """True when every item is at least as large as the one before it."""
    for i in range(len(values) - 1):
        if not values[i] <= values[i + 1]:
            return False
    return True


print(is_sorted([1, 2, 3]), is_sorted([3, 1]))
print(is_sorted([2, 5, 5, 8]), is_sorted([1, 1]))
```

*Equal neighbours allowed. code/grade-7/05-finding-and-fixing-bugs/exercises/is_sorted_fixed.py*

It prints `True False` and `True True`.

**Exercise 23.10 ★★★.**

Change the [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `average` of [Listing 23.2](#lst-g7-finding-and-fixing-bugs-two-calls) so that it returns 0 for an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) instead of stopping the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program).

**Solution of Exercise 23.10.**

A test before the division, which is never reached for an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list):

```python
def average(values):
    if len(values) == 0:
        return 0
    total = 0
    for value in values:
        total = total + value
    return total / len(values)


print(average([12, 10, 11, 9, 11]), average([]))
```

*An average with a guard. code/grade-7/05-finding-and-fixing-bugs/exercises/average_guard.py*

It prints `10.6 0`.

**Exercise 23.11 ★★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should add the even numbers from 1 to 10, which makes 30. It prints 25 and has two [bugs](#def-g7-finding-and-fixing-bugs-bug). Fix them one at a time, running after each fix, in both orders. Is the final [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) the same? Then why fix one at a time?

```python
n = 10
total = 0
for i in range(1, n):
    if i % 2 == 1:
        total = total + i
print("sum of the even numbers up to", n, ":", total)
```

***Listing 23.11.** Two [bugs](#def-g7-finding-and-fixing-bugs-bug). code/grade-7/05-finding-and-fixing-bugs/exercises/evens_bug.py*

**Solution of Exercise 23.11.**

The two [bugs](#def-g7-finding-and-fixing-bugs-bug): `range(1, n)` stops at 9, so it must be `range(1, n + 1)`; and `i % 2 == 1` picks the odd numbers, so it must be `i % 2 == 0`. Fixing the test first gives $2 + 4 + 6 + 8 = 20$, then 30; fixing the range first gives $1 + 3 + 5 + 7 + 9 = 25$ again, then 30. Both orders end with the same [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program), which prints 30:

```python
n = 10
total = 0
for i in range(1, n + 1):
    if i % 2 == 0:
        total = total + i
print("sum of the even numbers up to", n, ":", total)
```

*Both [bugs](#def-g7-finding-and-fixing-bugs-bug) fixed. code/grade-7/05-finding-and-fixing-bugs/exercises/evens_fixed.py*

Running after each fix tells you what each change did: in the second order, the first fix leaves the answer at 25, and only running shows that it was still needed. With both changes at once, a wrong result would not say which change was wrong.

**Exercise 23.12 ★★★.**

This [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) is right on most [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of marks. Find a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) on which it is wrong, the smallest one, and fix it.

```python
def largest(values):
    best = 0
    for i in range(1, len(values)):
        if values[i] > best:
            best = values[i]
    return best
```

***Listing 23.12.** The largest mark? code/grade-7/05-finding-and-fixing-bugs/exercises/largest_bug.py*

**Solution of Exercise 23.12.**

The [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) starts at [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) 1, so the first mark is never looked at, and `best` starts at 0. The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) is wrong when the largest mark is the first one: `[9, 3, 4]` gives 4. The smallest such [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) is a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of one mark, `[5]`, which gives 0. Starting with `best = values[0]` fixes both: the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) then prints `9 9 5` for `[3, 9, 4]`, `[9, 3, 4]` and `[5]`.

## 23.7 Problem: The Bug Hunt

**Problem 23.1.**

Weekend problem — four bugs in a grader

A teacher’s [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) gives a quiz score from 0 to 99 a letter (A from 90, B from 75, C from 50, D below) and a [comment](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-comment) from its tens digit (poor below 50, fair in the 50s and 60s, good in the 70s and 80s, great from 90). It has four [bugs](#def-g7-finding-and-fixing-bugs-bug): one [syntax error](#def-g7-finding-and-fixing-bugs-kinds), one [runtime error](#def-g7-finding-and-fixing-bugs-kinds) and two [logic errors](#def-g7-finding-and-fixing-bugs-kinds).

```text
# grader.py -- a letter and a comment for a quiz score from 0 to 99
WORDS = ["poor", "poor", "poor", "poor", "poor",
         "fair", "fair", "good", "good"]


def letter(score):
    if score > 90:
        return "A"
    elif score >= 75:
        return "B"
    elif score >= 50:
        return "C"
    else:
        return "D"


def comment(score)
    tens = score % 10
    return WORDS[tens]


def grade(score):
    return letter(score) + " (" + comment(score) + ")"


if __name__ == "__main__":
    for score in [45, 50, 75, 90, 99]:
        print(score, grade(score))
```

***Listing 23.13.** The grader, as the teacher wrote it. code/grade-7/05-finding-and-fixing-bugs/listings/grader.txt*

**Part I — The errors that stop the program.**

1. Before running it, find the [syntax error](#def-g7-finding-and-fixing-bugs-kinds) by reading.
2. Here is the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) run as it is, then run again with the colon added (the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) `grader_v1.py`). Which line does each report point to? `$ python grader.py File "~/session/grader.py", line 17 def comment(score) ^ SyntaxError: expected ':' $ python grader_v1.py 45 D (fair) 50 C (poor) 75 B (fair) 90 B (poor) Traceback (most recent call last): File "~/session/grader_v1.py", line 28, in <module> print(score, grade(score)) ^^^^^^^^^^^^ File "~/session/grader_v1.py", line 23, in grade return letter(score) + " (" + comment(score) + ")" ^^^^^^^^^^^^^^ File "~/session/grader_v1.py", line 19, in comment return WORDS[tens] ~~~~~^^^^^^ IndexError: list index out of range [exit status 1]` **Output 23.11.** Two runs, two reports.
3. Read the second report from the bottom. Which [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) failed, and with which score? Which [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) did `tens` have? Fix the [runtime error](#def-g7-finding-and-fixing-bugs-kinds) .

**Part II — Checking a hundred scores.** The [files](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) `grader_v2.py`, `grader_v3.py` and `grader_v4.py` are the grader after one, two and three more fixes. A checking [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) works out the expected grade another way and counts the wrong answers:

```python
import grader_v2
import grader_v3
import grader_v4


def expected(score):
    """The grade worked out another way: from the score's tens digit."""
    tens = score // 10
    words = ["poor"] * 5 + ["fair"] * 2 + ["good"] * 2 + ["great"]
    if score >= 90:
        letter = "A"
    elif score >= 75:
        letter = "B"
    elif score >= 50:
        letter = "C"
    else:
        letter = "D"
    return letter + " (" + words[tens] + ")"


for name, module in [("v2", grader_v2), ("v3", grader_v3), ("v4", grader_v4)]:
    wrong = []
    for score in range(100):
        if module.grade(score) != expected(score):
            wrong.append(score)
    print(name, len(wrong), "wrong answers out of 100, first ones:", wrong[:5])
```

***Listing 23.14.** Every score from 0 to 99. code/grade-7/05-finding-and-fixing-bugs/listings/check_grader.py*

4. Why is it safer to check against a second, simpler way of working out the grade than against answers typed by hand?
5. Run it. How many wrong answers does each version give?
6. Which [logic error](#def-g7-finding-and-fixing-bugs-kinds) was fixed between `v2` and `v3` , and which one between `v3` and `v4` ?
7. In Part I, the scores 45 and 75 got the [comment](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-comment) “fair”. Was that a sign of a [bug](#def-g7-finding-and-fixing-bugs-bug) ?

**Part III — The smallest inputs.**

8. Which is the smallest score that shows the [comment](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-comment) [bug](#def-g7-finding-and-fixing-bugs-bug) ? Why that one?
9. Which scores show the letter [bug](#def-g7-finding-and-fixing-bugs-bug) ? Which line of the [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) of Part I already showed it?
10. Had the letter [bug](#def-g7-finding-and-fixing-bugs-bug) been fixed first, how many wrong answers would remain? Why not 65?
11. State the result.

**Solution of Problem 23.1.**

**1.** Line 17, `def comment(score)`, has no colon at the end.

**2.** The first report points to line 17, the missing colon; the second, read from the bottom, to line 19, `return WORDS[tens]`.

**3.** `comment` failed, called by `grade` for the score 99. `tens` was 9, and `WORDS` has only nine [items](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), with indices 0 to 8: the word `"great"` is missing. Adding it fixes the [runtime error](#def-g7-finding-and-fixing-bugs-kinds).

**4.** Answers typed by hand can be mistyped, and there would be a hundred of them; a second [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) written another way is unlikely to make the same mistake as the first.

**5.**

```
$ python check_grader.py
v2 66 wrong answers out of 100, first ones: [5, 6, 7, 8, 9]
v3 1 wrong answers out of 100, first ones: [90]
v4 0 wrong answers out of 100, first ones: []
```

***Output 23.12.** 66, then 1, then 0 wrong answers.*

**6.** Between `v2` and `v3`, `score % 10` became `score // 10`: the [comment](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-comment) used the units digit instead of the tens digit. Between `v3` and `v4`, `score > 90` became `score >= 90`.

**7.** Yes: 45 should be “poor” and 75 “good”. Their units digit is 5, and `WORDS[5]` is “fair”.

**8.** The score 5: for 0 to 4 the units digit and the tens digit both pick “poor”, and 5 is the first score whose units digit picks another word.

**9.** Only 90, which gets a B. Part I’s [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) already showed it: the line `90 B (poor)`.

**10.** 66 still: the score 90 also has a wrong [comment](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-comment), so fixing its letter alone does not make its answer right.

**11.** **Result.** Among the scores 0 to 99, the grader gives 66 wrong answers once it runs, 1 after the [comment](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#def-g6-first-python-program-comment) is fixed and 0 after the letter is fixed.
