One of the simplest and most effective ways to debug your Python code—especially when you're just starting out—is by using the print()
function. It allows you to inspect variable values, control flow, and catch unexpected behavior quickly without needing external tools or setup.
While more advanced techniques like using pdb
or logging modules exist, print()
remains a go-to solution for quick debugging during development and prototyping.
1. Why Use print()
for Debugging?
- Easy to use and understand
- No setup required—just add a line of code
- Good for small scripts and quick testing
- Helps trace the flow of execution
2. Inspecting Variable Values
Print the value of variables to understand what your program is doing.
def calculate_total(price, quantity):
total = price * quantity
print(f"DEBUG: price={price}, quantity={quantity}, total={total}")
return total
calculate_total(10, 5)
Output:
DEBUG: price=10, quantity=5, total=50
3. Tracking Program Flow
Use print()
to confirm whether certain blocks of code are executed.
def check_number(x):
if x > 0:
print("DEBUG: Positive number detected")
return "Positive"
elif x < 0:
print("DEBUG: Negative number detected")
return "Negative"
else:
print("DEBUG: Zero detected")
return "Zero"
print(check_number(-3))
4. Debugging Loops
Print values inside a loop to monitor iteration behavior.
for i in range(5):
print(f"DEBUG: i={i}")
print(i * 2)
5. Printing Complex Structures
You can print lists, dictionaries, or even custom objects to examine their contents.
students = [
{"name": "Alice", "score": 90},
{"name": "Bob", "score": 85}
]
for student in students:
print(f"DEBUG: {student}")
print(f"{student['name']} scored {student['score']}")
6. Using print() with Conditional Statements
def is_even(n):
print(f"Checking if {n} is even...")
if n % 2 == 0:
print("DEBUG: Condition met — even number")
return True
else:
print("DEBUG: Condition failed — odd number")
return False
print(is_even(7))
7. Printing with Function Calls
Use print()
to track function calls and returns.
def multiply(x, y):
result = x * y
print(f"multiply({x}, {y}) = {result}")
return result
multiply(3, 4)
8. Avoid Leaving Debug Prints in Production Code
While print()
is helpful during development, it’s best to remove or replace them with proper logging before deploying code to production.
# Better for production:
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Informational message")
9. Tip: Use Distinct Messages
Prefix your debug print statements with something like "DEBUG:"
or "TRACE:"
so they’re easy to identify and separate from normal program output.
10. Final Thoughts
Using print()
is a beginner-friendly and effective way to debug Python programs. It helps you understand the internal workings of your code by revealing variable states and control flow. As your skills evolve, you may adopt more powerful debugging tools, but print()
will always be a valuable tool in your toolkit.