debugging in python for beginners
Tags: python, debugger, programming, beginners
Published: 2023-05-09 15:37:47

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

## **Debugging**

> 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
    print(num)
    if num > 1:
        for i in range(2, int(num/2)+1):
          
            #  print statement to check the value of i
            print(i)
            if num % i == 0:
                flag = False
                break
    else:
        flag = False

    return flag

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

```
**Output:
**
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18ewybz2o6czqbhe4f1t.png)<figcaption>Using print we can find where the error occurs in the code</figcaption>

## 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)
```
**Output:**

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mnzv8y99r2kz6j5yo912.png)<figcaption>the message will display what you have written along with the assertion statement
</figcaption>
## 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
`
**Steps:**

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
    else:
        return num * factorial(num-1)

print(factorial(5))
```
**Output:**

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/26qfjylk55tvqgax8l9n.png)
<figcaption>the debugger will pause execution at the breakpoint and enter interactive mode
here the code shows the value of num when the breakpoint executed</figcaption>

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)
    print(result2)

main()
```
**output**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezajw9rlo051uldeioq1.png)
<figcaption>debugging using ipdb debugger</figcaption>

## 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):
    try:
        result = x / y
    except ZeroDivisionError as e:
        logging.error("Tried to divide by zero: {}".format(e))
        result = None
    else:
        logging.info("Division successful: {} / {} = {}".format(x, y, result))
    return result


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

```
**output**
`5.0
None`

## 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:

- Python Tutor (http://pythontutor.com/)
- CodePad (http://codepad.org/)
- Repl.it (https://repl.it/)

## 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.