Print
Debugging
Learn to use print() to inspect variables, trace control flow, and find bugs in your Python programs: the simplest and most universal debugging technique.
What Is Debugging?
A bug is any behavior in your program that differs from what you intended. Debugging is the process of finding and fixing those bugs. Before you can fix a problem, you need to see what your code is actually doing.
Why Use print()?
Python's built-in print() function writes text to the console. By strategically placing print statements in your code, you can observe what is happening at each step without any special tools.
The Core Idea
Print debugging answers two fundamental questions about your running program:
Anatomy of a Print Debug Statement
Inspecting Variables
def calculate_average(scores): total = sum(scores) count = len(scores) print(f"DEBUG: total={total}, count={count}") average = total / count print(f"DEBUG: average={average}") return average result = calculate_average([85, 92, 78])
DEBUG: total=255, count=3 DEBUG: average=85.0
Tracing Control Flow
Sometimes the bug is not a wrong value but the code taking the wrong path. Place prints at branch points to see which path executes.
def classify_grade(score): print(f"DEBUG: entered classify_grade, score={score}") if score >= 90: print("DEBUG: took branch A (90+)") return "A" elif score >= 80: print("DEBUG: took branch B (80+)") return "B" else: print("DEBUG: took branch C (below 80)") return "C"
DEBUG: entered classify_grade, score=85 DEBUG: took branch B (80+)
print() vs Debugger Tools
| print() Debugging | IDE Debugger | |
|---|---|---|
| Setup | None: works everywhere | Requires IDE configuration |
| Speed | Add one line, re-run | Set breakpoints, step through |
| Interactivity | Output is fixed once printed | Can inspect any variable live |
| Learning Curve | Beginner-friendly | Moderate to advanced |
| Best For | Quick checks, loops, scripts | Complex state, large codebases |
How to Apply Print Debugging
Example 1: Finding an Off-by-One Error
This function should return the first N items of a list, but it returns one too few.
def first_n(items, n): result = [] for i in range(n - 1): # Bug is here! print(f"DEBUG: i={i}, adding {items[i]}") result.append(items[i]) print(f"DEBUG: result={result}") return result print(first_n(["a", "b", "c", "d"], 3))
DEBUG: i=0, adding a DEBUG: i=1, adding b DEBUG: result=['a', 'b'] ['a', 'b']
Example 2: Debugging a Loop
This function should count how many words in a list have more than 4 letters, but returns 0.
def count_long_words(words): count = 0 for word in words: print(f"DEBUG: word='{word}', len={len(word)}") if len(word) > 4: print(f"DEBUG: counted '{word}'") count = 0 # Bug! Should be count += 1 return count print(count_long_words(["hi", "hello", "world"]))
DEBUG: word='hi', len=2 DEBUG: word='hello', len=5 DEBUG: counted 'hello' DEBUG: word='world', len=5 DEBUG: counted 'world' 0
Example 3: Catching a Type Bug
This code reads user input and tries to double it, but gets unexpected string concatenation.
age = input("Enter your age: ") print(f"DEBUG: age={age}, type={type(age)}") double_age = age * 2 print(f"DEBUG: double_age={double_age}")
DEBUG: age=15, type=<class 'str'> DEBUG: double_age=1515
Debugging Inside Loops
Loops can produce hundreds of lines of output. Use these strategies to keep it manageable:
for i, val in enumerate(data): if i < 3 or i == len(data) - 1: print(f"DEBUG: i={i}, val={val}")
Useful f-string Patterns
# Self-documenting expression (Python 3.8+) x = 42 print(f"DEBUG: {x = }") # Output: DEBUG: x = 42 # Multiple variables at once print(f"DEBUG: {x = }, {y = }, {z = }") # Show type alongside value print(f"DEBUG: val={val!r} type={type(val).__name__}") # repr for strings (shows quotes and escapes) name = " Alice " print(f"DEBUG: name={name!r}") # Output: name=' Alice '
Common Mistakes
Print Debugging Cheat Sheet
| Goal | Code Pattern | When to Use |
|---|---|---|
| See a value | print(f"x={x}") | Variable seems wrong |
| Check type | print(type(x)) | Unexpected behavior |
| Trace path | print("reached A") | Code may be skipped |
| Loop state | print(f"i={i}, val={v}") | Wrong output from loop |
| Reveal whitespace | print(repr(s)) | String comparison fails |
| Self-documenting | print(f"{x = }") | Quick check (3.8+) |
Question 1 of 5
You have a function that should return the sum of a list, but it returns 0 every time. Which print statement would be most helpful as a first step?
Question 2 of 5
What does the following code print?
x = input("Number: ") # user types 3
print(f"DEBUG: {x}, {type(x)}")
Question 3 of 5
Your code crashes on line 10. You add print("reached line 10") on line 10, but it never appears in the output. What does this tell you?
Question 4 of 5
A loop runs 10,000 times and you want to debug it. Which approach is best?
Question 5 of 5
Which of the following is the most important step after you fix a bug using print debugging?