Back to results for “Profiling”
Python › Debugging & Profiling

How do you use print statements effectively for debugging, including showing variable names alongside values?

Beginner

Answer

Use an f-string with the '=' specifier (Python 3.8+) to automatically print both the variable's NAME and its value in one concise expression, avoiding the tedium of manually typing 'print(f"variable_name: {variable_name}")'.
count = 42
name = "Sam"
print(f"{count=}, {name=}")  # "count=42, name='Sam'" -- auto-includes the variable name
Real-world example Quickly checking a variable's current value and type during ad-hoc debugging without writing a full debug statement.

Common follow-ups: Why is print-based debugging generally considered less efficient than using a proper debugger for complex bugs?