目次
1. What is Debugging?
Debugging is the process of finding and fixing bugs (errors) in a program. It’s essential for any program, not just Python. Debugging skills improve a program’s quality and reliability and form the foundation for efficient development.Purpose of Debugging
The goal of debugging is to identify and fix hidden issues in the code. Ultimately, it aims for the program to run accurately and efficiently.Common Types of Errors in Python
Let’s look at the common error types in Python, along with their causes and solutions.- SyntaxError: A syntax error. It occurs when the code’s grammar is wrong, such as a typo in symbols or a missing colon.
- TypeError: An error caused by mismatched types. For example, trying to add an integer and a string triggers this.
- NameError: Occurs when an undefined variable or function is called. It can also happen due to misspellings.
- IndexError: Happens when you try to access an index outside the bounds of a list or tuple.
- ValueError: Raised when an inappropriate value is passed to a function or method.
2. Debugging Techniques in Python
Python supports a variety of debugging methods. Below we explain the most common approaches.Debugging with print statements
The simplest and most convenient method is usingprint
statements. You can display the value of specific variables or the progress of execution in the console.Example
def add_numbers(a, b):
result = a + b
print(f"Debug: result = {result}") # Debug print statement
return result
add_numbers(2, 3)
Advantages and Limitations
- Advantages: No setup or preparation needed, and it can be used instantly anywhere.
- Limitations: Overusing
print
statements reduces code readability, making them unsuitable for complex bugs.
Using the pdb Module
By usingpdb
, Python’s built‑in debugger, you can pause code execution and inspect the execution flow in detail.Basic Usage
- Setting a breakpoint: Use
pdb.set_trace()
to set a breakpoint on the line you want to debug. - Run: When you run the script, it pauses at the set breakpoint.
- Enter commands: Use the following commands to continue debugging.
Key Commands
n
: Move to the next line (step over)s
: Enter inside a function (step in)c
: Continue until the next breakpoint or program endp <variable name>
: Display variable values
import pdb
def calculate_total(a, b):
pdb.set_trace() # Pause here
result = a + b
return result
calculate_total(5, 3)
Debugging with an IDE
Integrated development environments (IDEs) for Python provide even more convenient debugging features. Visual Studio Code and PyCharm, in particular, are popular among Python developers.Debugging Features in Visual Studio Code
- Setting a breakpoint: Click the line you want to debug to set a breakpoint.
- Start debugging: Choose Run → Start Debugging.
- Inspect variables: You can view variable values while the program runs.
Debugging Features in PyCharm
- Setting a breakpoint: Set a breakpoint on the line you want to debug.
- Run in debug mode: Click the Debug button in the upper right.
- Real‑time monitoring: You can monitor variable values and object states in real time.
3. Tips for Effective Debugging
We’ll introduce tips and methods to make debugging more efficient.How to Read and Use Error Messages
Python error messages show the type of error and where it occurred. Carefully interpreting the message leads to faster problem resolution.Leverage Logging
Logging is a more suitable debugging approach thanprint
statements. Using the logging
module lets you record events and errors that occur during code execution.import logging
logging.basicConfig(level=logging.DEBUG)
def divide(a, b):
logging.debug(f"Divide function called with a = {a}, b = {b}")
if b == 0:
logging.error("Division by zero!")
return None
return a / b
divide(10, 0)
Logging is useful not only during development but also for tracking issues in production.Introducing Unit Tests
Unit tests help prevent errors that can arise from code changes. Below is an example using theunittest
module.import unittest
def add_numbers(a, b):
return a + b
class TestAddNumbers(unittest.TestCase):
def test_add_positive(self):
self.assertEqual(add_numbers(2, 3), 5)
def test_add_negative(self):
self.assertEqual(add_numbers(-2, -3), -5)
if __name__ == '__main__':
unittest.main()
Document Bug Reproduction Steps
If you can reproduce a bug, pinpointing its cause becomes easier. The more reproducible it is, the faster you can identify the cause, and the easier it is to spot similar bugs.
4. Introduction to Debugging Tools
Here, we introduce debugging tools useful for Python.pdb Module
pdb
is a debugger that comes standard. It features breakpoint setting with set_trace()
.Visual Studio Code
It’s a free IDE with rich Python debugging features. Because it can be operated via a GUI, even beginners can debug easily.Features
- Setting breakpoints
- Real-time variable monitoring
- Step execution
PyCharm
A Python-specific IDE with comprehensive debugging features. Ideal for large projects and team development.Features
- Powerful debugging options
- Real-time variable monitoring
- Detailed operations with breakpoints
Logging (logging) Module
logging
can capture detailed execution logs and is especially useful for recording error logs. It can also be used to track issues during development and operation.