print() and breakpoint()
In this lesson, you’ll learn how to debug in Python using
breakpoint() is an alias that works in Python 3.7 and newer for
import pdb; pdb.set_trace(), which works in all Python versions.
pdb is Python’s built in debugger and helps you step line by line through your code. If you want to learn more, check out Python Debugging With pdb.
In the video, you saw
float("inf"), which is a concise way to find the largest number (infinity). You can also use
-float("inf"), which finds the smallest possible number. Check out the Python Built-in Documentation to learn more.
Let’s look at two different ways to debug in Python. First, let’s look at print statements. Let’s write a function
max() that takes in our list and returns the max number without using the built-in
max() function. Let’s do this iteratively.
Why is that happening? Well,
max_num is never changing. We can verify that by printing a string here, like
'entered if statement', saving it, running it, and noticing it never enters the if statement.
Or, you could import the
math module and find the smallest number that way—I think there’s some variable there, but I like
float('inf'). It’s a little bit more explicit. Save it, run it, and we got
-1. So that worked using print statements.
So instead of printing, just write
breakpoint() and it’s a function, so you have to call it. And then, what will happen is as it’s executing the code, once it hits the
breakpoint() it will stop immediately there, and then you can print out variables and do all sorts of stuff.
Running it, it says line 5,
if num > max_num:. It’s right about to execute this code, but it hasn’t yet. You can print out
lst—stuff like that, and then you can type
n to go to the next line—line 6.
breakpoint() is very useful when there are many variables, or if there is very complicated logic, or if you’re really not sure—and so you just put the
breakpoint() in multiple spots in the code and just try to print stuff out—instead of the print statement, where you sort of have to know what you’re looking for.
I will link a Real Python article on
pdb, which will have all the commands and go way in-depth. I just wanted to expose you all to this great debugging tool. Also, if you’re doing a phone interview on a online code editor like HackerRank, they probably don’t have
pdb is really only if you’re doing it on your computer and they’re screen-sharing, or if you’re on an onsite and you’re using one of their computers. But a lot of times, interviewers may ask, “How would you debug this code?” and you can mention
pdb. In the next video, you will learn about f-strings, which are a new feature in Python 3.8 and newer.
Become a Member to join the conversation.