Python - Debugging
What is Debugging?
Debugging is the process of identifying and fixing errors (bugs) in your code. In Python, debugging tools help locate where your code goes wrong and why.
Why Debugging is Important
- Improves code quality and reliability
- Reduces runtime errors
- Helps understand complex bugs
- Essential for large-scale development
Common Debugging Methods
- print() Statements
- pdb - Python Debugger
- IDE Debugging Tools (PyCharm, VSCode)
- Logging for production-level debugging
1. Using print() Statements
Quick but not scalable. Useful for small scripts.
python
def divide(a, b):
print("a =", a) # Debug print
print("b =", b)
return a / b
result = divide(10, 0)
print(result)
2. Using pdb (Python Debugger)
pdb is an interactive source code debugger.
python
import pdb
def divide(a, b):
pdb.set_trace() # Start debugging
return a / b
divide(10, 0)
During execution, type commands like:
n– next linec– continue executionq– quit debuggerp var– print value ofvar
3. Using Logging Instead of print()
Preferred in production environments.
python
import logging
logging.basicConfig(level=logging.DEBUG)
def divide(a, b):
logging.debug(f"a = {a}, b = {b}")
return a / b
divide(10, 2)
4. Debugging in IDEs
Modern IDEs like PyCharm and VSCode have built-in debuggers that let you:
- Set breakpoints
- Inspect variables
- Step through code
- Watch expressions
5. Common Debugging Commands (pdb)
l– list source codep– print variables– step into functionb lineno– set breakpoint at liner– continue until return
6. Catching Exceptions
Using try-except blocks helps isolate faulty logic.
python
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
Best Practices
- Use logging over print statements
- Use IDE debugging for complex issues
- Combine exception handling with logging
- Use assertions to validate assumptions
Conclusion
Debugging is a fundamental part of development. From simple print statements to advanced IDE debuggers, Python offers flexible tools for finding and fixing errors efficiently.