Debugging is an essential skill in programming, helping you identify and resolve errors in your code efficiently. Python provides several built-in tools and practices for debugging.
Using print()
statements is one of the simplest ways to debug your code by displaying values of variables or execution flow.
# Example of debugging with print
number = 10
def increment(num):
print(f"Input number: {num}") # Debugging statement
return num + 1
result = increment(number)
print(f"Result: {result}")
Excessive use of print()
statements can clutter your code and make debugging harder for larger projects.
pdb
DebuggerPython includes a built-in debugger module, pdb
, for step-by-step execution and inspection of code.
l
(list): Display code around the current line.n
(next): Execute the next line.s
(step): Step into a function.c
(continue): Continue execution until the next breakpoint.import pdb
def divide(a, b):
pdb.set_trace() # Start debugging session
return a / b
result = divide(10, 2)
print(result)
The pdb
debugger is highly effective for tracking issues in complex logic or loops.
VSCode provides an integrated debugging environment with powerful features.
F5
or go to the Debug panel and select "Start Debugging."VSCode's debugging tools allow integration with extensions like Python Debugger for advanced functionality.
The logging
module provides a more structured approach to debugging compared to print()
.
DEBUG
: Detailed information for diagnostics.INFO
: General events.WARNING
: Something unexpected happened but not critical.ERROR
: More serious issues.CRITICAL
: Severe errors.import logging
logging.basicConfig(level=logging.DEBUG)
def add(a, b):
logging.debug(f"Adding {a} and {b}")
return a + b
result = add(5, 7)
logging.info(f"Result: {result}")
Use logging for production-ready debugging to avoid cluttering output and controlling verbosity.
Using try-except
blocks can help debug runtime errors by catching exceptions and displaying relevant information.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
Avoid suppressing exceptions silently; always log or display relevant information.
Objective: Identify and fix issues in the provided code.
numbers = [1, 2, 3, 4]
def multiply_by_two(nums):
for i in range(len(nums)):
nums[i] *= 2
return numbs # Typo in variable name
result = multiply_by_two(numbers)
print(result)
print()
to check intermediate values.pdb
to step through it.nums
during iterations using logging
.By mastering these debugging techniques, you can effectively identify and resolve issues in your Python programs!