Debugging Python code using breakpoint() and pdb
While developing an application or exploring some features of a language, one might need to debug the code anytime. Therefore, having an idea of debugging the code is quite necessary. Let’s see some basics of debugging using built-in function breakpoint() and pdb module.
We know that debugger plays an important role when we want to find a bug in a particular line of code. Here, Python comes with the latest built-in function breakpoint which do the same thing as pdb.set_trace() in Python 3.6 and below versions.
Debugger finds the bug in the code line by line where we add the breakpoint, if a bug is found then program stops temporarily then you can remove the error and start to execute the code again.
Syntax:
1) breakpoint() # in Python 3.7
2) import pdb; pdb.set_trace() # in Python 3.6 and below
Method #1 : Using breakpoint() function
In this method, we simply introduce the breakpoint where you have doubt or somewhere you want to check for bugs or errors.
def debugger(a, b): breakpoint() result = a / b return result print(debugger(5, 0)) |
Output :

In order to run the debugger just type c and press enter.

Commands for debugging :
c -> continue execution q -> quit the debugger/execution n -> step to next line within the same function s -> step to next line in this function or a called function
Method #2 : Using pdb module
As the same suggests, PDB means Python debugger. To use the PDB in the program we have to use one of its method named set_trace(). Although this will result the same but this the another way to introduce the debugger in python version 3.6 and below.
def debugger(a, b): import pdb; pdb.set_trace() result = a / b return result print(debugger(5, 0)) |
Output :

In order to run the debugger just type c and press enter.

Example :
def debugger(a): import pdb; pdb.set_trace() result = [a[element] for element in range(0, len(a)+5)] return result print(debugger([1, 2, 3])) |
Output :

Recommended Posts:
- Python | Basic Program Crash Debugging
- Python code to convert SOP to POS
- Issues with using C code in Python | Set 2
- Issues with using C code in Python | Set 1
- Code introspection in Python
- Different Python IDEs and Code Editors
- How to run Python code on Google Colaboratory
- Morse Code Translator In Python
- Packaging and Publishing Python code
- Optimization Tips for Python Code
- Execute a String of Code in Python
- Python | Generate QR Code using pyqrcode module
- Performing Google Search using Python code
- How to generate byte code file in python ?
- Understanding Code Reuse and Modularity in Python 3
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



