Bug Hunters Cheat Sheet STRICTLY CONFIDENTIAL FILE // DEBUG_01
Bug Hunters Field Guide
Python Debugging Cheat Sheet • Runtime Exceptions & Tracing
LEVEL: NOVICE TO PRO
SYS: PYTHON 3.x
1. LENNY NOW HAS EDITABLE ARTIFACTS!!
Exceptions occur when your syntax is correct, but Python encounters an unresolvable error during execution. Meet the top three offenders:
Index
IndexError ✨
List out of bounds
The Trigger
names = ["Alice", "Bob"]
print(names[2]) # IndexError!
Why it happens:
Accessing a list offset index that doesn't exist. Python is 0-indexed; maximum valid index is len(list) - 1.
Key
KeyError
Dictionary key missing
The Trigger
user = {"id": 101}
print(user["email"]) # KeyError!
Why it happens:
Requesting a key that doesn't exist in the dictionary. Avoid with key checking or safe .get("key", default).
Type
TypeError
Mismatched datatypes
The Trigger
age = "15" + 1
# TypeError: can't concat str
Why it happens:
Performing incompatible actions on differing types (e.g., adding text strings to integers). Python won't guess coercion.
2. Tracing Variable Values (Mental Trace Tables)
To isolate logical bugs (where code runs but produces wrong results), draw a Variable Trace Table to record state changes line by line.
The Suspect Code
1 total = 0
2 items = [2, 5]
3 for num in items:
4 total += num
5 total *= 2
6 print(total)
Trace Insight
Tracking code lines manually reveals exactly when total doubles unexpectedly in step 4.
STATE TRACE LOG OK // SECURE
Step
Line
num
total
0 (Init)
1-2
-
0
1 (It 1)
3-4
2
2 (0+2)
2
5
2
4 (2*2)
3 (It 2)
3-4
5
9 (4+5)
4
5
5
18 (9*2)
5 (End)
6
-
Prints 18
PYTHON BUG HUNTERS — MODULE 1: DETECTING EXCEPTIONS
PAGE 1 OF 2
STRICTLY CONFIDENTIAL FILE // DEBUG_02
The Debugging Toolkit
Python Debugging Cheat Sheet • Print Tracing & IDE Tools
LEVEL: NOVICE TO PRO
SYS: PYTHON 3.x
3. Weapon 1: Strategic Print Tracing
Make Python explain itself! Insert print() statements at critical lines to inspect hidden values during execution.
❌ BLIND EXECUTION Unhelpful
def avg_score(scores):
total = sum(scores)
count = len(scores)
return total / count
ans = avg_score([80, 90, 100])
Zero division bug remains hidden!
If an empty list is passed, you get a ZeroDivisionError but cannot see why.
✅ STRATEGIC LOGGING Trace Ready
def avg_score(scores):
print(f"DEBUG: scores={scores}")
total = sum(scores)
count = len(scores)
print(f"DEBUG: {total=}, {count=}")
return total / count
ans = avg_score([80, 90, 100])
DEBUG OUTPUT: DEBUG: scores=[80, 90, 100] | total=270, count=3
PRINTING CHEAT SHEET STRATEGIES
1. Label Your Values: Use print(f"{x=}") which displays as x=10 automatically.
2. Track Branch Flow: Print inside loops or checks: print("Inside IF block") to confirm paths.
3. Production Cleanup: Delete or comment out diagnostic print statements before submitting code.
4. Weapon 2: Using IDE Breakpoint Tools
An interactive debugger pauses code execution at any specific line (Breakpoint) so you can inspect live variable states without modification.
DEBUGGER CONTROL PANEL PAUSED ●
🔴
Breakpoint
Python pauses execution before this line, enabling full inspection.
Step Over (Next Line)
Runs current line and moves to next line. Runs function calls silently.
Step Into
Jumps inside the function definition to trace internals step-by-step.
Step Out
Runs remainder of function and pauses right after the function exits.
Resume / Continue
Resumes program execution until next breakpoint or termination.
IDE PANEL VIEW WATCH
// ACTIVE VARIABLES
scores = [80, 90]
total = 170
count = 2 LIVE
// CALL STACK
> avg_score()
module.()
💡 Debuggers don't alter code files like temporary print commands do, preventing leftover tracing bugs!
PYTHON BUG HUNTERS — MODULE 2: INSTRUMENTATION & TOOLS
PAGE 2 OF 2
Bug Hunters Worksheet STUDENT MISSION LOG // LEVEL 1
Bug Hunters Worksheet
NAME:
DATE:
CLASS:
Apply your debugger training to identify common runtime exceptions, trace state mutations, and isolate logical bugs.
A SPOT THE EXCEPTION (Runtime Investigations)
Analyze each broken snippet. Identify the exact **Exception Type** (e.g., IndexError, KeyError, TypeError) and write a 1-sentence **explanation & fix**.
# Case #101
inventory = {"apples": 5, "pears": 3}
item = "bananas"
qty = inventory[item]
print("Total qty:", qty)
1. IDENTIFIED EXCEPTION TYPE:
2. WHY DID IT CRASH & HOW WOULD YOU PREVENT IT?
# Case #102
level = 4
msg = "You are at level " + level
print(msg)
1. IDENTIFIED EXCEPTION TYPE:
2. WHY DID IT CRASH & HOW WOULD YOU PREVENT IT?
B TRACE TABLE TRAINING (Logical Debugging)
Trace the values of variables as Python executes this loop. Fill in the empty table rows step-by-step.
// TRACE CODE CHASSIS
1 val = 15
2 steps = [1, 3]
3 for num in steps:
4 val -= num
5 val *= 2
6 print(val)
⚠️ Remember: Keep track of every iteration! Write down intermediate expressions to make sure you get the correct arithmetic.
STUDENT LOGGING MATRIX PENDING INPUT
Step
Line
num
val
0 (Init)
1-2
-
15
1 (Iter 1)
2
3 (Iter 2)
4
5 (Final Output)
Prints:
PYTHON BUG HUNTERS — MISSION LOG 1 // IDENTIFYING & TRACING
PAGE 1 OF 2
STUDENT MISSION LOG // LEVEL 2
LENNY NOW HAS EDITABLE ARTIFACTS!
STATION: LOGIC LAB
SCORE: 100 / 100
C STRATEGIC PRINT INSTRUMENTATION
Examine this logic error. The developer wants to count how many words in a list start with letter "a", but it keeps printing 0.
# Buggy Code Chassis
1 words = ["apple", "banana"]
2 count = 0
3 for w in words:
4 first_letter = w[1]
5 if first_letter == "a":
6 count += 1
7 print("A counts:", count)
1. At which line number would you insert a diagnostic print() statement to check if the loop is selecting the correct character?
2. Write the exact line of Python code for a diagnostic print statement that prints the current word w and its checked first_letter:
D IDE DEBUGGER ACTION MATRIX
Circle or check the correct tool behavior depending on your current target goal during interactive debugging.
1
Your code execution is paused on Line 8, which is: scores_sum = aggregate(score_list). You suspect there is a logical calculation bug inside the aggregate function. Which debugger control should you click next?
[ ] Step Over [ ] Step Into [ ] Resume/Cont
2
You have set a red breakpoint at Line 15. The program is currently paused on Line 15. You have diagnosed the variables mentally, fixed the design logic, and now want to allow the script to execute completely to the end without checking any more single lines. Which debugger control should you click next?
[ ] Step Over [ ] Step Into [ ] Resume/Cont
E CODE SURGERY (Rewrite to Cure)
Rewrite the buggy loop from Section C so it operates correctly, selects the correct first letter, and outputs the accurate count (1). Keep your work clean...
PYTHON BUG HUNTERS — MISSION LOG 2 // CODESMITH REPAIRS
PAGE 2 OF 2
Bug Hunters Answer Key TEACHER REFERENCE
Answer Key & Solutions
Lesson: Bug Hunters • Document Reference Solution Guide
MASTER SOLUTION KEY
STATUS: VERIFIED // 100%
A Section A: Spot the Exception (Key & Explanations)
Case #101 (inventory dictionary search) KeyError
1. Exception Type:
KeyError
2. Root Cause & Correction Method:
The key "bananas" is queried but doesn't exist in the dictionary. Prevent by initializing "bananas": 0 or using inventory.get("bananas", 0).
Case #102 (string + int addition) TypeError
1. Exception Type:
TypeError
2. Root Cause & Correction Method:
Attempted to concatenate an integer 4 to a string using +. Fix by wrapping level with str(level) or using f-string f"level {level}".
B Section B: Trace Table Training (Solution Matrix)
Correct variables trace path showing how values undergo mutations line-by-line during loop cycles.
COMPLETED TRACE RECORD EXPECTED OUTPUT: 50
Step
Line
num
val (Mutated State)
Operation Mechanics
0 (Init)
1-2
-
15
Initialize val = 15, steps list
1 (Iter 1)
3-4
1
14
val = 15 - 1
2
5
1
28
val = 14 * 2
3 (Iter 2)
3-4
3
25
val = 28 - 3
4
5
3
50
val = 25 * 2
5 (Final)
6
-
Prints 50
Correct Terminal Output
PYTHON BUG HUNTERS — TEACHER SOLUTION GUIDE
PAGE 1 OF 2
TEACHER REFERENCE
Facilitation & Codesmithing
Lesson: Bug Hunters • Pedagogy & Remaining Solutions
MASTER SOLUTION KEY
STATUS: VERIFIED // 100%
C-D Sections C & D: Instrumentation & Decisions
SECTION C: STRATEGIC PRINTING
1. Insertion Line Number:
Line 5 (or Line 4.5)
2. Ideal Debug Print Code:
print(f"{w=}, {first_letter=}")
Or equivalence: print(w, first_letter). The key is printing values inside the loop to verify index selections.
SECTION D: DEBUGGER DECISIONS
1. aggregate() logical bug:
Step Into (jumps into function block)
2. Complete execution normally:
Resume / Continue (stops step trace debugging)
E Section E: The Final Fix (Corrected Loop)
words = ["apple", "banana"]
count = 0
for w in words:
first_letter = w[0] # FIXED: Index changed from [1] to [0]
if first_letter == "a":
count += 1
print("A counts:", count)
Bug Explanation: Python sequences are 0-indexed. Using w[1] selected the second letter ("p" in "apple" and "a" in "banana"), resulting in an inaccurate total count. Changing to w[0] correctly targets the first character.
Teacher Facilitation Notes
⚠️ Common Misconceptions
0-Indexing: Students frequently mix up the first element index as 1 instead of 0, leading directly to logical bugs in strings and lists.
Step Over vs Into: Students struggle to understand that "Step Over" executes functions without opening their internal code lines.
💬 Guiding Questions
"If a list has a length of 5, why is index 5 out of bounds?" (Encourage counting from zero: 0, 1, 2, 3, 4).
"What is the difference between an error that crashes your program immediately vs. code that prints the wrong math?"
PYTHON BUG HUNTERS — TEACHER SOLUTION GUIDE
PAGE 2 OF 2