🛟 Errors & Exceptions, lesson 6 of 6
Debugging strategies
Hunt down wrong answers with print debugging, repr and assert.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
The trickiest bugs don't crash: the program runs but gives the wrong answer. No traceback points at these logic errors, so you need a method:
- Reproduce it with the smallest failing input
- Inspect values as the code runs
- Check assumptions with
assert - Change one thing, re-run, repeat
Print debugging a wrong answer
f"{n=}" prints a name and its value. The debug
line shows count also goes up for -2. Indent
count += 1 under the if, run again, then delete
the debug print.
repr reveals sneaky values
Plain printing hides the newline and makes "5" and
5 look identical. Fix the comparison with
answer.strip() == "yes".
assert: check your assumptions.
assert condition, "message" does nothing when the
condition is true and raises AssertionError with
your message when it's false. Put them where something
must be true, and bugs get caught close to where they
start. (The exercises in this app check your code with
asserts too!)
assert catches a bad value early
Without the assert, the second call would quietly return a negative price (-120.0).
What does this print?
Your function returns the wrong number but never crashes. What's the best first step?
Fix the vowel counter
count_vowels runs without crashing but gives wrong
answers. There are two logic bugs. Use print
debugging to find and fix them.
More habits of good debuggers:
- Read the whole error message before changing code
- Test edge cases: empty lists, 0, negatives,
"" - Explain your code line by line out loud (rubber duck debugging). You'll often hear the bug
- Remove debug prints once you're done