00:00 Sometimes using a debugger can be tricky and time-consuming, but it is the most reliable way to find bugs in your code. However, debuggers aren’t always available. Systems with limited resources, such as small Internet-of-things devices, they often won’t have built-in debuggers. What can you do in these cases?
00:19 Does that mean that there’s going to be a swarm of bugs that’s just going to take over your code, and there’s nothing you can do about it? No. In situations like this, you can use print debugging to find bugs in your code.
Print debugging uses the
print() function to display text in the console that indicates where the program is executing and what the state of the program’s variables are at a certain point in your code. For example, instead of debugging the previous program with the Debug window, you could add
print() statements into the
for loop and then just run it directly and inspect the output.
01:00 You can see that the interactive window tells me that Debug is now off. I will also remove this breakpoint. And if I now run the script, it’s just going to run from start to finish and print out the result.
Again, you would guess where the bug probably lies and you would come to the same conclusion: it’s somewhere inside of the
for loop. But now instead of using the debugger, you can insert a
print() function here and print out some information about the current state of the program.
You can see that in the first duration of the loop, the character is
'h' and the
new_word looks like this: you have an
h followed by an underscore. However, the initial underscore is not there. In the next iteration, you can see that it’s replaced by
'e_', et cetera. And then finally, you see the output of the
print() function at the end of your script, that just holds the final letter of the word and an underscore.
03:01 So this gives you a similar output as the variable inspector panels for the local and global variables inside of your Debug Control window, but it is not as flexible. Print debugging works, but it has several disadvantages over debugging with a debugger. First, you have to run your entire program each time that you want to inspect the values of your variables.
So overall, using a debugger is the preferred way of debugging your programs, but if you don’t have access to a debugger, then you can also use the
print() function to get some insight into the state of your program at certain points in time.
Become a Member to join the conversation.