Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 5 of 15

print-based debugging

Using print statements effectively: the f-string = specifier, tracing loops and function calls, printing types and reprs, and graduating to the logging module with levels so debug output can be switched off.

Beginner 8 min read·Lesson 283 of 306 in Python Programming

Learning objectives

  • Print informative debug output
  • Trace loops and function calls
  • Replace prints with logging levels

Definition

Print debugging means adding temporary output statements that show the values of variables and the path of execution. The logging module provides the same benefit with levels, formatting and the ability to turn messages on and off.

Introduction

The quickest debugger is print(). Used well — labelled, targeted and temporary — it finds many bugs in seconds.

Why it matters

Print debugging works everywhere, including servers and scripts where a graphical debugger isn't available. logging makes it permanent and controllable.

Detailed explanation

Label every debug print so you know what you're looking at. The f-string = specifier does it automatically: f"{total=}" prints total=42.

Print repr(value) or use !r to see exact contents: trailing spaces, quotes and types ('5' versus 5).

Trace loops by printing the iteration variable and key state each time; trace functions by printing arguments on entry and the result on exit.

Print type(value) when a value might not be what you expect.

Remove or disable debug prints when finished; forgotten prints confuse users and clutter output.

The logging module replaces ad-hoc prints: logger.debug, info, warning, error and critical. The configured level decides which messages appear.

logging.basicConfig sets the destination, level and format (including the function name and time) in one call.

Logging calls take arguments separately (log.debug("total=%s", total)) so formatting only happens when the message is shown.

Syntax

Python
print(f"{total=}, {items=!r}")
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
log.debug("total=%s", total)
  • Label debug output.
  • Use repr to see exact values.
  • Use logging for switchable output.

Code examples

Self-labelling prints

Python
x = 3
name = "Asha "
print(f"{x=}, {x * 2=}, {name=}")
Output
x=3, x * 2=6, name='Asha '

Tracing a loop

Python
def running_max(nums):
best = nums[0]
result = []
for i, n in enumerate(nums):
if n > best:
best = n
print(f"debug: i={i} n={n} best={best}")
result.append(best)
return result
print(running_max([3, 1, 4, 1, 5]))
Output
debug: i=0 n=3 best=3
debug: i=1 n=1 best=3
debug: i=2 n=4 best=4
debug: i=3 n=1 best=4
debug: i=4 n=5 best=5
[3, 3, 4, 4, 5]

More examples

From prints to logging

Python
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG,
format="%(levelname)s:%(funcName)s:%(message)s", force=True)
log = logging.getLogger("shop")
def apply_discount(total, code):
log.debug("total=%s code=%s", total, code)
if code == "SAVE10":
total *= 0.9
elif code:
log.warning("unknown code %r", code)
return round(total, 2)
print(apply_discount(500, "SAVE10"))
print(apply_discount(500, "FREE"))
logging.getLogger().setLevel(logging.WARNING)
print(apply_discount(200, "BAD"))
Output
DEBUG:apply_discount:total=500 code=SAVE10
450.0
DEBUG:apply_discount:total=500 code=FREE
WARNING:apply_discount:unknown code 'FREE'
500
WARNING:apply_discount:unknown code 'BAD'
200

Step-by-step explanation

  • Debug messages show inputs on every call while the level is DEBUG.
  • Raising the root level to WARNING hides the debug lines without touching the function.
  • The warning about an unknown code still appears because it is important.

Expected output

Running “From prints to logging” prints exactly:

TextOutput
DEBUG:apply_discount:total=500 code=SAVE10
450.0
DEBUG:apply_discount:total=500 code=FREE
WARNING:apply_discount:unknown code 'FREE'
500
WARNING:apply_discount:unknown code 'BAD'
200

Practical applications

  • Server logs that record warnings and errors permanently.
  • Quick checks while developing a script.

Best practices

  • Label and target debug output.
  • Use repr for strings.
  • Switch to logging for anything you'll keep.

Common mistakes

Unlabelled prints

Avoid

print(x)
print(y)
print(x)

Prefer

print(f"{x=} {y=}")

Bare numbers in the output are impossible to tell apart.

Leaving debug prints in

Avoid

print("HERE!!!") # shipped to users

Prefer

log.debug("reached checkout")

Logging can be silenced; stray prints cannot.

Important notes

  • pprint.pprint shows nested data structures in a readable layout.

Key takeaways

  • f"{x=}" labels values automatically.
  • Trace loops and calls with targeted prints.
  • logging adds levels and control.

Try it yourself

  1. 1
    Add tracing prints to a buggy function that should reverse words in a sentence and find the bug.
  2. 2
    Convert the prints in one of your scripts to logging with DEBUG and INFO levels.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic