How to debug your code like a pro?

How to debug your code like a pro?

·

6 min read

One of the most difficult and time-consuming components of programming is debugging code. Bugs can emerge whenever you least expect them and can be challenging to find and correct, whether you are working on a little script or a large-scale application. You can learn how to debug your code like a pro, though, and spare yourself time and hassles in the process by using a few important approaches and tools.

  1. Understand The Problem

Understanding the problem is the first and most important step in debugging your code. Without a clear understanding of what the problem is, it can be difficult to know where to start looking for solutions. In this section, we will discuss some techniques you can use to understand the problem you are trying to solve.

#Let's look at an illustration of code:
def divide_numbers(a, b):
    result = a / b
    return result
#Suppose we are using this function to divide two numbers, but it is giving us unexpected results. Our first step should be to examine the code and try to identify any potential issues.

#One thing we can do is to add print statements to the function to track the flow of data and see how variables are changing:*/

def divide_numbers(a, b):
    print(f"a={a}, b={b}")
    result = a / b
    print(f"result={result}")
    return result
#By adding these print statements, we can see the values of a and b before the division is performed, and we can see the resulting value of result. This can give us clues about what might be going wrong.

#Another thing we can do is to test the function in different scenarios. For example, we can test what happens if we divide by zero:

result = divide_numbers(10, 0)

#When we run this code, we get a ZeroDivisionError. This tells us that the function is not handling the case of dividing by zero correctly.

#Finally, we can look for error messages or warnings that might provide clues about what is going wrong. For example, if we run our code with a linter, we might get a warning that the function is not handling the case of dividing by zero:
division_by_zero.py:2: warning: Division by zero
    result = a / b
#This warning tells us that we need to add some error handling code to our function to handle the case of dividing by zero.

#By using these techniques to understand the problem, we can get a better idea of where to start looking for solutions. In this example, we might add some error handling code to our function to prevent the ZeroDivisionError:

def divide_numbers(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    result = a / b
    return result

In summary, understanding the problem is a critical step in debugging your code. By examining the code, testing it in different scenarios, and looking for error messages or warnings, you can get a better idea of what is going wrong and where to start looking for solutions.

  1. Separate the problem:

In order to isolate the problem, the troublesome part of code must be reduced by deleting superfluous code and concentrating on the precise location that is causing the issue. By doing so, the problem's scope is narrowed and its underlying causes are easier to find.

Consider that you are developing a Python program that computes the total of all the numbers in a list. You observe, nevertheless, that the output of your software is inaccurate. You can start by commenting out unrelated code or print statements and concentrating just on the code that calculates the sum in order to isolate the problem. Here's an illustration:

numbers = [1, 2, 3, 4, 5]
total = 0

# Calculate sum of numbers
for number in numbers:
    total += number

# Print the result
print("The sum of numbers is: ", total)

#Let's say that this code gives you an incorrect result. To isolate the issue, you can comment out the print statement, so that you can focus on the calculation of the sum:

numbers = [1, 2, 3, 4, 5]
total = 0

# Calculate sum of numbers
for number in numbers:
    total += number

# Print the result
print("The sum of numbers is: ", total)

You may now rerun the program to check that the overall amount is what you anticipate it to be. If it is, you will know that there is a problem somewhere and not with the sum's computation. If it continues to be inaccurate, you know that the for loop is where the problem is.

You can use a debugger to pause the program at particular lines and look at the state of variables to further isolate the problem. This enables you to observe what is taking place inside the loop and aids in the detection of any errors.

  1. Use Print Statements

Suppose we have a function that takes in a list of numbers and returns the sum of those numbers. However, we're noticing that the function is returning an incorrect result, so we want to debug it using print statements.

def sum_numbers(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

numbers_list = [1, 2, 3, 4, 5]
result = sum_numbers(numbers_list)
print(result)

We have a function called sum_numbers that takes in a list of numbers and returns the sum of those numbers. We also have a list of numbers called numbers_list that we want to pass into the function.

To debug the code using print statements, we can add print statements throughout the function to track the flow of data and see how the total variable changes as the program runs.

def sum_numbers(numbers):
    total = 0
    for num in numbers:
        print("Adding", num, "to total:", total)
        total += num
        print("New total:", total)
    return total

numbers_list = [1, 2, 3, 4, 5]
result = sum_numbers(numbers_list)
print(result)

In this updated version of the function, we've added two print statements inside the for loop. The first print statement prints out the current number being added to the total and the current value of the total. The second print statement prints out the new value of the total after the current number has been added. Now, when we run the program, we can see the output of the print statements and track the flow of data as the program runs. This can help us identify any issues with the code and pinpoint where the problem is occurring.

  1. Use Assertions:
def divide(a, b):
    assert b != 0, "Error: denominator cannot be zero"
    return a / b

print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Output: AssertionError: Error: denominator cannot be zero

The divide function takes two parameters a and b, and returns the result of a divided by b. However, if b is zero, dividing by it would result in an error. To catch this error early on, we add an assertion statement that checks whether b is not equal to zero. If the condition is not met, an assertion error is raised with a custom error message. In the first print statement, the function is called with valid arguments, and it returns the expected output of 5.0. In the second print statement, the function is called with b set to zero, which triggers the assertion error and prints the custom error message.

Did you find this article valuable?

Support Ali Aliyev by becoming a sponsor. Any amount is appreciated!