DEV Community

Keerthiga P
Keerthiga P

Posted on

Debugging

1. What is Debugging?

Debugging is the process of finding and fixing errors (bugs) in a program.

Bugs can be:

  • Syntax errors (code cannot run)
  • Logical errors (wrong output)
  • Runtime errors (program crashes while running)

2. Why Do We Use Debugging?

Debugging is important because:

  • ✅ Helps find the cause of errors
  • ✅ Makes programs run correctly
  • ✅ Helps understand program flow
  • ✅ Saves time instead of guessing what went wrong

3. How to Use Debugging?

There are several ways to debug:

a) Print Statements

Check variables and program flow using print() (optional for small programs).

b) Using Debugger in IDE

Most IDEs (VS Code, PyCharm, Eclipse) have built-in debuggers:

  • Set Breakpoints → pause execution at a line
  • Step Into / Step Over → go line by line
  • Watch Variables → check values while running
  • Call Stack → see which function called which

c) Dry Run (Manual)

Go line by line on paper with sample input to trace program flow.

4. Example: Debugging a Factorial Function in Python
Code with Error:

def factorial(n):
    return n * factorial(n - 1)  # Missing base case
print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

Problem: Infinite recursion → program crashes.

Fix by Adding Base Case:

def factorial(n):
    if n == 0:        # Base case added
        return 1
    return n * factorial(n - 1)
print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

Output:

120
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Base case stops recursion at n = 0
  • Recursive call now reduces n each time
  • Program works correctly without crashing

Top comments (0)