20/20
Debugging & Best Practices Β· Page 1 of 1

Debugging, Logging & Assertions

Debugging & Best Practices

Using print() vs Logging

print() is fine for quick scripts, but logging is professional:

import logging

# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug("Detailed diagnostic info")
logger.info("General informational message")
logger.warning("Something unexpected!")
logger.error("A serious problem occurred")
logger.critical("The program may not continue!")

Assertions for Data Validation

Assert that your assumptions about data are true:

def process_scores(scores):
    assert isinstance(scores, list), "scores must be a list"
    assert len(scores) > 0, "scores cannot be empty"
    assert all(0 <= s <= 100 for s in scores), "all scores must be 0-100"
    
    return sum(scores) / len(scores)

When to use assertions: Catch programmer errors, not user errors.

Debugging with pdb

Python Debugger β€” set breakpoints and step through code:

import pdb

def buggy_function():
    x = 10
    pdb.set_trace()  # Execution pauses here
    y = x / 0        # Debugger lets you inspect x before this crashes

Code Quality Best Practices

  1. Name variables clearly: user_age not a
  2. Use type hints (modern Python): def calculate(x: int) -> float:
  3. Write docstrings: Explain why, not just what
  4. Keep functions small: One responsibility each
  5. Use constants for magic numbers: MAX_RETRIES = 3
Done
main.py
Loading...
OUTPUT
β–ΆClick "Run Code" to execute…