CS 111
Fall 2018

Debugging Tips

Judiciously Use Print Statements

Use strategically-placed print statements to reveal the values of key variables. It is usually helpful to have a print statement at the beginning of the function to print out what the values of the parameters are, and to have print statements before any return statements so you can view what is being returned for the given function all. Putting too many print statements can cause too much irrelevant information to be printed, which can be very confusing.

Do a Step-by-Step Trace

Trace through the function by hand or by using the Online Python Tutor to visualize the execution of the code. This requires you to engage the code by either tracing it yourself as if you were the computer, or stepping through the execution line-by-line to determine what happens. Either way, you are forced to look at the code meticulously and can often spot errors.

Thoroughly Test the Code

Some problems will only show up after thoroughly testing the code. Be sure to check as many cases as you can think of, especially the “edge” cases that may happen rarely but will break your code. A good rule of thumb is to always test functions that accept string parameters with the empty string and to test functions that accept numerical parameters with negative numbers and zero.

The Python Shell is a great tool to test your functions, since you can quickly make many different function calls and easily view their output.

When creating a large program, you should test each function you write before moving on to the next function. Otherwise, after creating many functions you may realize that there are bugs, but they can be very difficult to find since you are not sure which functions are correct and which have problems.

Become Familiar with Common Errors

Take the time to review the list of Common Python Errors that we have compiled for you. If you encounter one of these errors, this page may be able to give you enough information to diagnose and fix the bug. If you come across an error that you don’t recognize and don’t know how to solve, post it on Piazza so that you can get help and we can add the error to the list.