How do you use print statements effectively for debugging, including showing variable names alongside values?
Short 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}")'.
Advertisement
AModel 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 nameReal-world example
Quickly checking a variable's current value and type during ad-hoc debugging without writing a full debug statement.
Likely follow-ups
- Why is print-based debugging generally considered less efficient than using a proper debugger for complex bugs?
Related topics