Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.10 — Debugging: breakpoint(), pdb and Reading State
Python · Example 1 of 5

Print debugging done well

Read the labelled lines, find where the data shrinks, then fix the condition (use v is not None) and run again.

Debugging is finding the first place where what your program holds differs from what you believed. You can do it with well-labelled prints, with breakpoint() and the pdb debugger, with your editor's debugger, and with a systematic method such as bisection.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 7 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a function first_negative(numbers) that returns the first negative number, or None if there is none. Call it with [3, 8, -2, 5] and print the result with print(f"{result=}"). It should print result=-2.

02

The function def total(items): return sum(item["price"] * item["qty"] for item in items) fails with KeyError: 'qty' on one item. Take a list of three dictionaries where one has no "qty" key. Write a loop that prints the position (counting from 0) of each item that is missing qty. Hint: enumerate gives you the position.

03

Using the bisect idea, find the first whole number from 1 to 1000 whose square is at least 50000. Count the checks as you go, and print the number and the count on one line. Hint: copy the while low < high loop and change the test to mid * mid >= 50000.

Explain it without notes

01

Describe a systematic way to debug a program that gives a wrong answer.

02

What does breakpoint() do, and what are the basic pdb commands?

03

Why is the line shown in a traceback not always where the bug is?

04

What is bisection and how does it apply to debugging?

Print debugging done well
Sign in to run this example in your browser.

Expected output

data=[5, 0, 7, None, 3]
cleaned=[5, 7, 3]
len(data)=5 len(cleaned)=3
lost=[0, None]