Debugging Your Code
Learn how to find and fix bugs like a professional developer.
Learning Objectives
- Understand common types of bugs
- Use 'print debugging' effectively
- Learn basic use of the Python debugger (pdb)
- Understand the concept of a 'Rubber Duck'
Solving the Mystery
Bugs are a natural part of programming. A “bug” is just a mistake in your logic that causes the program to behave unexpectedly. Today, we learn the mindset and the tools needed to fix them.
Type of Bugs
- Syntax Errors: Mistakes in your typing (e.g.,
prnit("Hello")). Python finds these for you. - Runtime Errors: Mistakes that happen while the app is running (e.g.,
1 / 0). - Logic Errors: The app runs fine, but the result is wrong (e.g., calculating
price + discountinstead ofprice - discount).
The Power of print()
The simplest way to debug is to “trace” your code by printing variable values at different steps.
|
|
Using the Debugger (pdb)
Python comes with a built-in debugger called pdb. It allows you to pause your code and look around.
|
|
When the program hits set_trace(), it stops. You can type variable names (like x) to see their values before the next line runs.
Rubber Duck Debugging
Sometimes, the best way to find a bug is to explain your code line-by-line to an inanimate object (like a rubber duck). As you explain what you think the code is doing, you often realize what it is actually doing.
Interactive Practice
Imagine a loop that should print numbers 1 to 5 but only prints 1 to 4. Where would you put a print() statement to check the loop condition?
Quiz
Complete this quiz with a minimum score of 80% to mark Day 25 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!