Debugging in VS Code
Debugging in VS Code
Sometimes your code runs, but the result is wrong.
Sometimes it crashes and you do not know why.
Instead of guessing, you can use a debugger.
VS Code has a built-in debugger that helps you inspect your program step by step.
What Is Debugging?
Debugging means finding and fixing problems in code.
Problems can be:
- syntax errors
- runtime errors
- logic errors
Why Use a Debugger?
A debugger helps you:
- pause code
- inspect variables
- run line by line
- understand program flow
- find bugs faster
Example Problem
total = 0
for number in [1, 2, 3]:
total = number
print(total)
Output:
3
But the expected total should be:
6
A debugger helps you see why.
Important Debugging Tools
Breakpoint
A breakpoint pauses the program on a line.
In VS Code:
- Click left of the line number
- A red dot appears
Run and Debug
Use:
- Run menu
- Or press
F5
Choose Python file.
Step Over
Runs the next line.
Useful for moving line by line.
Variables Panel
Shows current variable values.
Example:
total = 1
number = 1
Corrected Code
total = 0
for number in [1, 2, 3]:
total += number
print(total)
Output
6
Example 2: Check Input
age = int(input("Enter age: "))
print(age + 5)
Use a breakpoint after input to inspect age.
Useful Debugging Steps
- Run the program
- Add breakpoint
- Watch variables
- Step through code
- Find wrong logic
- Fix code
- Test again
When to Use print()
print() debugging is still useful for quick checks.
Debugger tools are better for larger programs.
Code Along
Create code with a wrong total.
Use the debugger to find and fix it.
Mini Challenge
This code is wrong:
count = 0
for n in [2, 4, 6]:
count =+ n
print(count)
Tasks:
- Run it
- Debug it
- Fix it
Expected output:
12
Real World Use Case
Developers use debuggers to fix apps, websites, automation scripts, games, and business tools.
Quiz
- What is debugging?
- What does a breakpoint do?
- What key starts debugging in VS Code?
- Why use a debugger instead of guessing?
Assignment
Create a small program with a bug. Use the debugger to find and fix it.
Summary
You learned how to use the VS Code debugger with breakpoints, step-by-step execution, and variable inspection.