Python
Python

 

 

🧠 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

  1. Save the code in a file named debug_example.py.
  2. Open terminal or command prompt.
  3. Run the code with: python debug_example.py
  4. Observe the error and fix it using the steps above.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)