Assertions catch the first wrong state
The failure names the exact value that broke the rule, right where it first appears.
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.
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.
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.
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
Describe a systematic way to debug a program that gives a wrong answer.
What does breakpoint() do, and what are the basic pdb commands?
Why is the line shown in a traceback not always where the bug is?
What is bisection and how does it apply to debugging?
Expected output
10 -> 180.0
50 -> 100.0
150 -> state check failed: percent out of range: 150