How to Debug Code
What is a Debugger? 🐞
A debugger is a tool that lets you pause your code while it’s running so you can inspect what’s happening internally. In Python, this means you can:
- ✅ View the values of variables at any point.
- ✅ Step through code one line at a time.
- ✅ Set breakpoints (places to pause code).
- ✅ Trace logic and fix issues more efficiently.
IDE-based debuggers (like those in VS Code and PyCharm) make this process accessible even for beginners.
When Should I Debug My Code? 🤔
You should consider using a debugger when:
- Your program is running, but not behaving as expected.
- You’re getting confusing error messages.
- You want to better understand how your code flows.
- You’re working with unfamiliar code.
Before you blindly copy-paste code from Stack Overflow or ChatGPT, run it through a debugger.
Just because it looks right doesn’t mean it is — debugging helps you understand what the code is actually doing, not just what it claims to do.
Debugging in Different IDEs 💻
If you haven’t installed an IDE yet, visit our Data Science Setup to install the necessary tools and environments.
Visual Studio Code offers powerful built-in debugging tools and supports many languages through extensions.
Key features include:
- Run and Debug View to manage sessions and configurations.
- Breakpoints to pause code execution at specific lines.
- Debug Toolbar for stepping through code, pausing, and restarting.
- Debug Console to inspect and evaluate variables during a session.
To get started, open a Python file, press F5
, and interact with your code using breakpoints and the debug panel.
PyCharm makes it easy to trace and fix bugs using its built-in debugger.
Key features include:
- Breakpoints: Click the gutter next to a line of code to pause execution there.
- Debug Toolbar for stepping through code, pausing, and restarting.
- Threads & Variables Panel: Inspect objects, variables, and their current values.
- Watch Expressions: Track specific variables over time by adding them to the watch list.
- Inline Debugging: See variable values directly in the editor as you step through the code.
To get started, add a breakpoint by clicking next to a line number, then click the green bug icon to run your code in debug mode. Use the Debug panel to inspect variable values and control the execution flow.