Debugging a program
In an ideal world, your program would do exactly what you want, i.e., realizing the algorithm it implements, hence solving your problem. However in practice, writing a program is a hard task.
There is a wide variety of ways to ensure a program works as intended (or at least try to). Here are some examples:
- Handmade debugging;
- Unit tests;
- Program provers;
- etc.
Here, we give a small list of rules of thumb to help you debug your programs as you write them. More complex approaches will be presented in other courses you may follow later in your engineering studies.
Do not wait to finish to run your program
Writing a non-trivial program takes (at least) some dozens of lines of code. A good way to ensure you are writing something that will be functional is to execute your program everytime you finish writing a few lines.
At the very least, this will help you check that all your variables are well written, since the Python interpreter will crash if you use a variable my-variable
after defining my_variable
(note the difference between – and _).
Don’t hesitate to use the print
function extensively in order to examine the state of your variables upon execution of the program. In particular, print(dir(my_variable))
gives information on the functions and attributes of my_variable
. Additionally, print(type(my_variable))
will show the type of my_variable
.
Test on controlled examples
You are writing a program for computing the number of elements in a list? Do not trust your function until you have run a couple of times on handwritten lists for which you know the answer, especially on extreme cases (an empty list for instance).
Go*gle your problem
Python provides error messages that are in general quite clear. However, if you do not understand the cause of the error, you can simply copy-paste the error message in your favorite search engine. There is a very high chance somebody has already encountered the same problem, and a nice person on StackOverflow already explained it.
RTFM
Sometimes, you want to write something complex (say, replacing all letters A in a text with a *), and start doing everything from scratch (here, iterating over all letters to check characters individually and build a new string), taking you several hours of hard work. However a function to do what you want is already available in the official Python documentation and could have taken you 5 minutes to find.
To go further
- A small presentation of Coq: A few words on solutions that exist to prove computer programs, as one would prove a mathematical theorem.