Command Palette

Search for a command to run...

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

Bisecting a bug

Seven checks find the first bad version out of 100. Change 64 to another number and see that the count stays about the same.

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?

Bisecting a bug
Sign in to run this example in your browser.

Expected output

check 1: version 50 is ok
check 2: version 75 is broken
check 3: version 63 is ok
check 4: version 69 is broken
check 5: version 66 is broken
check 6: version 65 is broken
check 7: version 64 is broken
first bad version: 64 after 7 checks