Debugging Techniques
Fundamental Debugging Strategies
Print Debugging
Simple yet effective debugging method:
def calculate_sum(a, b):
print(f"Input values: a={a}, b={b}") ## Trace input values
result = a + b
print(f"Result: {result}") ## Verify calculation
return result
Python Debugger (pdb)
Interactive debugging module for in-depth problem analysis:
## Launch script with debugger
python3 -m pdb script.py
Debugging Commands
Command |
Function |
n (next) |
Execute next line |
c (continue) |
Continue execution |
p (print) |
Print variable value |
l (list) |
Show current code context |
Error Handling Techniques
graph TD
A[Exception Handling] --> B[Try-Except Blocks]
B --> C[Specific Exception Catching]
C --> D[Logging Errors]
Exception Tracing
import traceback
try:
## Risky code block
result = 10 / 0
except Exception as e:
print(f"Error occurred: {e}")
traceback.print_exc() ## Detailed error traceback
Logging Mechanisms
Python Logging Module
import logging
## Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s: %(message)s'
)
def complex_function():
logging.info("Function started")
try:
## Function logic
logging.debug("Processing data")
except Exception as e:
logging.error(f"Error in function: {e}")
cProfile Module
python3 -m cProfile script.py
Best Practices
- Use meaningful variable names
- Implement comprehensive error handling
- Utilize logging instead of print statements
- Break complex problems into smaller, testable units
By mastering these debugging techniques on LabEx and other platforms, developers can efficiently diagnose and resolve Python launch and runtime issues.