Chapter 12

Testing and Debugging

There are always times when your code won't do what it should be doing. You see the inputs and work through the code, but somehow, it spits out an output that just shouldn't be possible. This can be one of the most infuriating parts of programming.

Investigating Bugs by Printing Out the Values

There are loads of ways to find out exactly what's happening, but one of the simplest is judicious use of print() statements. By using these to print out the value of every variable, you can usually get to the bottom of what's going on.

Take a look at the following code for a simple menu system. It doesn't produce any errors, but whatever input you give it, it always says "Unknown choice". (It's on the website as chapter12-debug.py):

choices = {1:"Start", 2:"Edit", 3:"Quit"}for key, value in choices.items():    print("Press ", key, " to ", value)user_input = input("Enter choice: ")if user_input in choices.values():    print("You chose", choices[user_input])else:    print("Unknown choice")

Perhaps you've seen the problem already, but if you haven't, what's the best way to find it? The problem is that the if statement isn't correctly identifying when the user_input is valid, so add some print() statements to see what's happening:

choices = {1:"Start", 2:"Edit", 3:"Quit"}for key, value in choices.items():    print("Press ", key, " to ", value)user_input = input("Enter choice: ")print("user_input: ", user_input)print("choices: ", choices)print("choices.values(): ...

Get Learning Python with Raspberry Pi now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.