01 / 21
>_

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.

Python

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.

Syntax Errors
Python cannot parse your code at all: missing colons, unmatched parentheses
Runtime Errors
Code runs but crashes midway: dividing by zero, accessing missing keys
Logic Errors
Code runs without crashing but gives the wrong result: hardest to find

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.

Zero Setup
Works in any Python environment: no installs, no imports, no configuration
Universal
Available in every programming language in some form: console.log, System.out, fmt.Println
Immediate
See output the moment your code reaches that line: real-time insight into execution

The Core Idea

Print debugging answers two fundamental questions about your running program:

1. What value does this variable hold?
Insert print(variable) to reveal the actual content at that moment in time
2. Did execution reach this line?
Insert print("reached here") to confirm which branches and loops actually run

Anatomy of a Print Debug Statement

print ( f "DEBUG: x = {x}, type = {type(x)}" ) Function f-string Label + Value Type check Prefix "DEBUG:" easy to find/remove

Inspecting Variables

Python
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])
Console Output
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.

Python
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"
Console Output (score=85)
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

1
Reproduce the bug. Run the code and confirm you see the wrong behavior.
2
Form a hypothesis. Guess where the problem might be: a calculation, a condition, input data.
3
Add labeled print statements around the suspected area. Print variable names and values.
4
Run and read the output. Compare actual values to what you expected.
5
Narrow down. If the bug is not here, move your prints. Repeat until you find the exact line.
6
Fix the bug, then remove all debug prints. Never leave them in finished code.

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.

Buggy Code
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))
Console Output
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.

Buggy Code
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"]))
Console Output
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.

Buggy Code
age = input("Enter your age: ")
print(f"DEBUG: age={age}, type={type(age)}")
double_age = age * 2
print(f"DEBUG: double_age={double_age}")
Console Output (user types "15")
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:

1
Print the iteration number: Include i or a counter so you know which pass caused the issue.
2
Use conditional prints: Only print when a condition is met, e.g., if i == 5: print(...).
3
Print first and last: Print on the first iteration and the last to compare start vs. end state.
4
Print summaries: After the loop, print the final accumulated value rather than every step.
Example
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

Python 3.8+
# 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

✕ Bare print(x)
Printing without a label: you see "42" but have no idea which variable that is.
✕ Leaving Prints In
Forgetting to remove debug prints before submitting. Use a "DEBUG:" prefix to search and delete them.
✕ Printing Too Late
Putting the print after the crash line. The program never reaches it. Print before the suspected line.
✕ Ignoring Type
The value looks right ("5") but it is a string. Always check type() when confused.

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?