How to Add a Breakpoint in Jupyter Notebook
Last Updated :
08 Sep, 2024
Debugging is a crucial aspect of programming that allows us to track down issues in our code. Setting breakpoints helps in pausing the code execution to inspect the current state, check variable values, and step through our code line by line. In Jupyter Notebooks, debugging can be done interactively using the ipdb library, which is designed for interactive environments like notebooks.
In this article, we’ll explore how to set and use breakpoints in Jupyter Notebook effectively.
Using the ipdb Package for the addition of breakpoint in Jupyter Notebook
Although Python's built-in breakpoint() function (available in Python 3.7 and later) is designed to pause the execution of code for debugging, it may not always work as expected in Jupyter Notebook due to the interactive nature of the environment.
To reliably set breakpoints in Jupyter Notebook, we use the ipdb package, which is specifically designed for interactive debugging in environments like Jupyter. ipdb.set_trace() allows us to pause the execution of our code and enter an interactive debugging session.
Steps to Use ipdb in Jupyter:
Install the ipdb package: If we don’t have the ipdb package installed, we can install it using the following command:
!pip install ipdb
Set a Breakpoint with ipdb.set_trace(): After installing ipdb, we can replace breakpoint() with ipdb.set_trace() in our code. When the execution reaches this line, the program will pause, and we can interactively inspect variables and step through our code.
Example:
Python
import ipdb
def divide(a, b):
result = a / b
ipdb.set_trace() # Execution will pause here
return result
# Call the function
divide(10, 2)
Output:
OutputKey Features of ipdb:
- Interactive Debugging Session: We can inspect variables and execute commands interactively within the Jupyter Notebook interface.
- Step Through Code: Use commands like next (or n) to move through our code line-by-line.
The %debug Magic Command for Post-Mortem Debugging
In addition to using ipdb.set_trace() to set breakpoints at specific locations in our code, Jupyter Notebooks also provide the %debug magic command. This command allows us to inspect the state of the program after an exception is raised, enabling post-mortem debugging.
Using %debug:
- Run a piece of code that raises an exception.
- Once the error occurs, type %debug in a new cell and execute it.
- Jupyter will open an interactive debugging session where we can inspect variables and navigate the stack trace.
Example:
Python
def faulty_function():
a = 10
b = 0
return a / b # This will raise a ZeroDivisionError
# Call the function to trigger an error
faulty_function()
Output:
Output
After running this code, a ZeroDivisionError will occur. To enter the debugging session, we would type %debug in the next cell:
Python
Output:
Breakpoint
We can then inspect variables like a and b, and step through the execution to understand the cause of the error.
Example of Setting a Breakpoint with ipdb
Let’s now walk through a complete example using ipdb to set a breakpoint and inspect the execution of the code interactively.
Example Code:
Python
import ipdb
def calculate_sum(numbers):
total = 0
for num in numbers:
total += num
ipdb.set_trace() # Pause the execution to inspect 'total' and 'num'
return total
# Call the function with a list of numbers
result = calculate_sum([1, 2, 3, 4, 5])
print("Total Sum:", result)
Output:
Breakpoint using idbpExplanation:
- Setting the Breakpoint: The execution will pause every time the loop encounters the ipdb.set_trace() line, allowing us to inspect the current values of num and total.
- Interactive Debugging: Once the execution pauses, we can check the values of variables by typing their names (e.g., num or total), step through the code using next, or continue execution with continue.
Debugging Commands:
- next (or n): Move to the next line in the current function.
- continue (or c): Continue the program until the next breakpoint or the end of the program.
- quit: Exit the debugging session.
- p variable_name: Print the value of a specific variable (e.g., p total).
Conclusion
Setting breakpoints is a crucial debugging technique, and using ipdb.set_trace() is a reliable way to add breakpoints in Jupyter Notebooks. While Python’s built-in breakpoint() may not always work in Jupyter, ipdb offers interactive debugging capabilities that integrate smoothly with the notebook interface. Additionally, the %debug magic command allows for post-mortem debugging when errors occur. Together, these tools can greatly improve our debugging experience in Jupyter Notebooks.
Similar Reads
How to Hide all Codes in Jupyter Notebook
Jupyter Notebooks have become indispensable tools for data scientists, researchers, and educators alike. They provide an interactive and dynamic environment for writing code, documenting processes, and presenting results. However, when it comes to sharing your work, particularly in lectures or prese
4 min read
How to upload a dataset in Jupyter Notebook?
Jupyter Notebook is a web-based powerful IDE tool that helps with data analysis, visualization and narrative multi-media. Uploading a dataset is a very common task when working in the Jupyter Notebook. It is widely used by data analysts, data scientists, researchers and other developers to perform d
4 min read
How To Delete Cell In Jupiter Notebook
Jupyter Notebook is a powerful tool for developers. Jupyter is an open-source web application that contains both code and text elements such as figures, questions, pictures, etc. Jupiter's main meaning is Julia, Python, and Ruby. Jupyter Notebook is a web-based computational environment for creating
3 min read
How to Add a Table of Contents in the Jupyter Notebook
In this article, we will cover How to add a table of contents to the Jupyter Notebook. First, we look at what Jupyter Notebook and table of contents and why we use them, followed by a step-by-step tutorial to add a table of contents to the Jupyter Notebook. Jupyter NotebookThe Jupyter Notebook is th
4 min read
How to Add R to Jupyter Notebook ?
Although Jupyter has an R studio for R Programming Language, many people prefer to work in the Jupyter Notebook as it is convenient to use. Add r in Jupyter Notebook we start with our system, which should have Anaconda installed. So, now let's set up the Jupyter Notebook for the R Programming Langua
1 min read
How to Delete Markdown in Jupyter Notebook
In this article, we will cover How to delete markdown in Jupyter Notebook we will discuss various methods to do the same. First, we look at what is Jupyter Notebook and markdown and why we use them, we discuss different methods to delete a markdown in Jupyter Notebook in this article. Jupyter Notebo
4 min read
How to Write and Run Code in Jupyter Notebook
Jupyter Notebook is an open-source web application. It allows to generate and share documents that contain live code, equations, visualized data, and many more features. Nowadays it has become the first choice of many of the data scientists due to it's immense data visualization and analysis capabil
7 min read
How to Fix Kernel Error in Jupyter Notebook
Jupyter Notebook is an open-source framework that comes under Anaconda software. It is a free cloud-based interactive platform used for computing in different types of languages. It is used for data analysis, visualizations, numerical calculations and simulations, equations, executing codes, machine
15 min read
How to Customize Line Graph in Jupyter Notebook
In this article, we will learn how to customize a line graph in Jupyter Notebook, we will discover different customization options available to customize the line graph we will use matplotlib library to generate and customize line graphs we will understand each option by looking it into the syntax a
6 min read
How to Install BeautifulSoup in Jupyter Notebook
Installation of BeautifulSoup on Jupyter Notebook is quite easy, and you will be all set for excellent web scraping and data extraction. It is a Python library that makes HTML and XML dealing with web data. It will help you get up and running with BeautifulSoup inside your Jupyter Notebook, so you c
5 min read