CodingNic

Error Handling and Debugging

Debugging in VS Code

Error Handling and Debugging 28 min read

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

python
total = 0

for number in [1, 2, 3]:
    total = number

print(total)

Output:

text
3

But the expected total should be:

text
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:

text
total = 1
number = 1

Corrected Code

python
total = 0

for number in [1, 2, 3]:
    total += number

print(total)

Output

text
6

Example 2: Check Input

python
age = int(input("Enter age: "))
print(age + 5)

Use a breakpoint after input to inspect age.

Useful Debugging Steps

  1. Run the program
  2. Add breakpoint
  3. Watch variables
  4. Step through code
  5. Find wrong logic
  6. Fix code
  7. 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:

python
count = 0

for n in [2, 4, 6]:
    count =+ n

print(count)

Tasks:

  • Run it
  • Debug it
  • Fix it

Expected output:

text
12

Real World Use Case

Developers use debuggers to fix apps, websites, automation scripts, games, and business tools.

Quiz

  1. What is debugging?
  2. What does a breakpoint do?
  3. What key starts debugging in VS Code?
  4. 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.