DEV Community


Posted on

debugging in python for beginners

In this article, we will discuss some of the commonly used debugging techniques in Python, such as debugger tools, modules, IDEs, etc.


Debugging is an essential part of software development. It helps find and fix errors in the code, resolving errors, or bugs, in a software system. Python has several built-in debugging tools and techniques that make it easier for developers to identify and resolve issues in their programs and continues the flow of code.

Let us see a few methods that can be used to debug code in Python.

Debugging using Print() statements

One of the simplest and easiest methods of debugging is using print() statements. By checking with print statements in different parts of the code, we can check the flow of the code, i.e where the code is getting the errors. Sometimes we are worried about why the output is wrong even after writing the correct syntax. But the actual problem is somewhere else. So, this technic can help you to find the error when your code is logically incorrect.
Example: Check if a number is a prime number or not.

def checkPrime(num):
    flag = True

    # print statement to check the number
    if num > 1:
        for i in range(2, int(num/2)+1):

            #  print statement to check the value of i
            if num % i == 0:
                flag = False
        flag = False

    return flag

# here we are passing a string instead of an integer
n = checkPrime("11")
if n == True:
    print("Prime number")
    print("Not a Prime number")

Enter fullscreen mode Exit fullscreen mode


In this example, the first print statement is used to check the number that is entered to check if it is a prime number or not. We can see the number passed to the function is of string type because it is enclosed within the double quotes. And when we tried to run the code, it first printed the value of 'num' because of the print statement and then generated the error.

Image description
Using print we can find where the error occurs in the code

Debugging using Assertion Statements

Assertion statements are used to check the validity of a statement in the code. It is just like a condition/limitation of inputs or values that is going under the code. Beyond these limits, the code may give errors. If the assertion statement evaluates to false, then it raises an AssertionError.

Example: Calculate the area of a rectangle

length = 10
# here we given negative value
breadth = -5 
assert length > 0 and breadth > 0, "Length and Breadth should be greater than 0"
area = length * breadth
print("The area of the rectangle is", area)
Enter fullscreen mode Exit fullscreen mode


The error message associated with the assertion statement will usually provide information about the cause of the error. The assertion error helps to detect the issue early on before it can cause further problems in the code.

Image description
the message will display what you have written along with the assertion statement

Debugging using Debuggers

Python has several debuggers like pdb (Python Debugger) and *ipdb *(IPython Debugger) that allow developers to step through the code and check the values of variables at different stages of execution. Debuggers will pause execution at the breakpoint and enter interactive mode.

To debug the program using pdb, we can run the following commands:
import pdb
pdb.set_trace() # breakpoint


  1. - Import the pdb module in your Python code.
  2. - Add a breakpoint at the line of code where you want to start debugging.
  3. - Once the breakpoint has been set, run the program as usual.
  4. - Use the various commands given below to move in the flow of the program.
  5. - Once you have finished debugging, you can analyze the code and fix any issues that you
  6. - identified during the debugging process.

We can use various commands like _next, step, and continue _to navigate through the code.

  • n or next: Execute the current line and move to the next line of code.
  • s or step: Execute the current line and step into any function calls on that line.
  • c or continue: Continue running the program until the next breakpoint is encountered.
  • p or print: Print the value of a variable.
  • q or quit: Quit the debugger and exit the program.

Example: Find the factorial of a number

import pdb

def factorial(num):
    pdb.set_trace()   #breakpoint of debbuging
    if num == 0:
        return 1
        return num * factorial(num-1)

Enter fullscreen mode Exit fullscreen mode


the debugger will pause execution at the breakpoint and enter interactive mode here the code shows the value of num when the breakpoint executed

To debug the program using ipdb, it is the same as the pdb:

The debugger pauses the compiler at the execution of breakpoint by the ipdb, it is better than pdb in some views like:

  • Colorized output: ipdb provides colorized output in the debugger console.
  • Improved syntax highlighting: ipdb has improved syntax highlighting compared to pdb.
  • Better support for interactive debugging: ipdb provides better support for interactive debugging.
  • Command aliases: ipdb allows you to define custom command aliases.
import ipdb

def multiply(x, y):
    result = x * y
    return result

def add(x, y):
    result = x + y
    return result

def main():
    x = 5
    y = 10
    result1 = multiply(x, y)
    ipdb.set_trace()   #breakpoint created by ipdb
    result2 = add(result1, y)

Enter fullscreen mode Exit fullscreen mode


Image description

debugging using ipdb debugger

Debugging using the Logging Module

Logging is an alternative to using print statements for debugging. It provides a way to track the flow of the program and record important events and error messages. Here are the steps to use Logging for debugging in Python:

  • Import the logging module in your Python code.
  • Configure the logging module with the desired output format, log level, and destination.
  • Add logging statements at various points in your code to track the flow of the program and find errors.
  • Once the program has been run, you can analyze the log output to find errors and track the flow of the program. *Example: *
import logging

# configure the logger
logging.basicConfig(filename='example.log', level=logging.DEBUG)

def divide(x, y):
        result = x / y
    except ZeroDivisionError as e:
        logging.error("Tried to divide by zero: {}".format(e))
        result = None
    else:"Division successful: {} / {} = {}".format(x, y, result))
    return result

# test the function
print(divide(10, 2))
print(divide(5, 0))

Enter fullscreen mode Exit fullscreen mode


Online Debugging Websites for Python

There are several free online debugging websites that allow developers to test and debug their code without installing any additional software. Some of the popular online debugging websites are:

Debugging using IDEs for Python

In addition to the built-in debugging techniques, there are various Integrated Development Environment(IDE) that provides a number of third-party debugging tools available for Python. Here are a few examples:

PyCharm: PyCharm is a popular Python IDE that includes a number of debugging features, such as breakpoints, step-by-step debugging, and variable inspection.
Spyder: Spyder is another popular Python IDE that includes a built-in debugger with similar features to PyCharm.
VSCode: Visual Studio Code is a lightweight but powerful code editor that includes a number of debugging features for Python, including breakpoints, variable inspection, and step-by-step debugging.

These tools can be especially helpful when you are working with large, complex codebases or when you need to debug code that is running in a production environment.

Top comments (0)