🧠 Introduction
Every programmer encounters bugs — it’s part of the journey! Debugging is the process of identifying and fixing those bugs to make sure your Python code runs as expected. Whether you’re getting unexpected results or your program is crashing, learning how to debug effectively is a crucial skill.
🎯 Objective
This guide is designed to help Python beginners understand how to spot and fix common errors in their code using built-in tools and simple techniques. You’ll learn how to use print statements, the pdb
debugger, and get hands-on with a small example.
💻 Python Code Example with a Bug
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
average = total / len(numbers)
return average
# Intentional bug: empty list passed in
data = []
result = calculate_average(data)
print("Average is:", result)
Expected Behavior: It should print the average of the numbers.
Actual Behavior: It crashes with ZeroDivisionError if the list is empty.
🔧 How to Debug
1. Use print statements to trace the values:
print("Data received:", data)
print("Length:", len(data))
2. Use Python’s built-in debugger:
import pdb; pdb.set_trace()
Place this before the line causing the error to step through the code interactively.
3. Fix the bug: Add a condition to handle empty lists.
def calculate_average(numbers):
if not numbers:
return 0 # or raise ValueError("Empty list provided")
total = sum(numbers)
return total / len(numbers)
🧩 Program Structure & Execution
- Function:
calculate_average
takes a list and returns the average. - Bug: An empty list causes division by zero.
- Fix: Add a check to avoid dividing by zero.
▶️ How to Run the Program
- Save the code in a file named
debug_example.py
. - Open terminal or command prompt.
- Run the code with:
python debug_example.py
- Observe the error and fix it using the steps above.