Skip to main content

Section 9.11 Programming Phase 2: Debugging

Here’s our non-working code again:
Beginning programmers are tempted to start changing the code a litte bit to see if that fixes the problem. If it doesn’t, they change a little bit more, and keep doing that until the code works. (You might have been tempted to do that as well.)
This is an approach that you would never stand for in any other part of your life. If you took your car to a mechanic and asked them to fix it, and they told you “OK. I’ll start replacing parts until the car starts working better”, you would immediately take your business elsewhere. Yet somehow, programmers (even advanced programmers) will use this “try changing the code and see if that fixes it” approach first rather than diagnosing the problem, which is what the mechanic would do as their first step.
One way to diagnose problems is to use debug output; you put print statements in your program to see what the values of variables are. (Or you can use codelens here in this book.)
Put this statement on line six. The p in print should be indented to line up with the i in if (it should be inside the loop and after the if statement):
print(f"Index is {index}: {a_list}")
Run the program and take a look at the output. Does this give you an idea of what is going wrong, and how to fix it? We will analyze this on the next page.