Introduction:
Debugging is the skill which I feel very few do it perfectly. But it is a must-have skill for every programmer.
In Python, you can easily debug your code with the help of python’s breakpoint()
function.
Note: There are other ways to debug your Python code, the most common way is to use your IDE’s debugger such as PyCharm. VSCode also comes with a great built-in debugger.
Let’s do it:
Debugging starts by creating a breakpoint.
- Create a breakpoint by inserting the
breakpoint()
function just before the suspected line.
a = 1
b = 0
breakpoint()
c = a/b # ZeroDivisionError
- Whenever the Python interpreter hits this
breakpoint()
method, it will pause the execution and wait for your response in the terminal. - In the terminal, you have a Python shell like interface called 'pdb shell', where you can access all the variables, function, etc. of the current execution context.
- There are some shortcut keys for navigating in the ‘pdb shell’. For listing all the shortcuts, you can use help command by entering
h
.
Note: breakpoint()
only works above Python 3.7, to debug on older versions of Python, you should use 'pdb 'module as given in below example.
import pdb
a = 1
b = 0
pdb.set_trace()
c = a/b # ZeroDivisionError
For more such crispy blogs daily, follow DevJunction, subscribe to our newsletter and get notified.
Social Links
- LinkedIn: https://www.linkedin.com/in/mnamegaurav/
- YouTube: https://www.youtube.com/c/devjunction
- Website: https://gaurav.devjunction.in/
- GitHub: https://github.com/mnamegaurav
- Instagram: https://www.instagram.com/mnamegaurav/
- Twitter: https://twitter.com/mnamegaurav