杰瑞科技汇

Python IDLE如何开启调试模式?

Of course! Debugging in Python IDLE is a fundamental skill that every beginner should learn. IDLE's built-in debugger is a simple but powerful tool that allows you to step through your code line by line, inspect variables, and find the exact source of an error.

Python IDLE如何开启调试模式?-图1
(图片来源网络,侵删)

Here’s a complete guide on how to use the Python IDLE debugger, from basic concepts to a practical walkthrough.


What is a Debugger?

A debugger is a tool that lets you control the execution of your program. Instead of running the entire program at once and seeing the final result (or a crash), you can:

  • Pause execution at specific points (called breakpoints).
  • Step through your code one line at a time.
  • Inspect the current values of your variables at each step.
  • See exactly which lines of code are being executed and in what order.

This is incredibly useful for understanding program flow and finding "bugs" (errors) that aren't obvious.


The IDLE Debugger Interface

When you start the debugger, a new window appears, called the Debug Control window. This is your command center.

Python IDLE如何开启调试模式?-图2
(图片来源网络,侵删)

Here are its key components:

  1. Stack: Shows the "call stack," which is the chain of function calls that led to the current line of execution. It's usually not needed for simple scripts but is great for understanding complex programs.
  2. Locals: This is the most important panel for beginners. It shows you all the variables that are currently defined in the scope of the line you're about to execute, along with their current values. This is where you look to see if your variables have the values you expect.
  3. Source: Displays the name of the file you are currently debugging.
  4. Buttons: These control the execution flow (we'll cover these next).

The Debugging Buttons

The buttons in the Debug Control window let you move through your code.

Button Name Action Analogy
Go Go Executes your program until it finishes, hits a breakpoint, or raises an unhandled exception. Pressing the "Go" button on a remote control.
Step Step Executes the very next line of code and then pauses again. If the next line is a function call, it will step into that function. Taking one single step on a staircase.
Over Over Executes the very next line of code and then pauses. If the next line is a function call, it will execute the entire function and then pause on the line after the function call. Stepping over a puddle without looking in it.
Out Out Continues execution until the current function is finished and returns. It "steps out" of the current function. Walking quickly to the top of a staircase after being on a lower flight.
Quit Quit Stops the debugger entirely and closes the Debug Control window. Your program will be terminated. Turning off the remote control.

Practical Walkthrough: Let's Debug a Script

Let's create a simple script with a bug and use the debugger to find it.

Step 1: Write the Code with a Bug

Open IDLE, create a new file (File -> New File), and paste the following code. Save it as find_bug.py.

Python IDLE如何开启调试模式?-图3
(图片来源网络,侵删)
# find_bug.py
def find_average(numbers):
    """Calculates the average of a list of numbers."""
    total = 0
    for num in numbers:
        total = total + num
    # Oops! There's a bug here.
    average = total / len(numbers)
    return average
def main():
    my_scores = [88, 92, 100, 75, 85]
    my_average = find_average(my_scores)
    print(f"The average score is: {my_average}")
    # Let's try with an empty list to see what happens
    empty_scores = []
    empty_average = find_average(empty_scores)
    print(f"The average of an empty list is: {empty_average}")
if __name__ == "__main__":
    main()

If you run this script directly (Run -> Run Module), it will crash with a ZeroDivisionError because you can't divide by len([]) (which is 0).

Step 2: Start the Debugger

  1. Do not run the script yet! Instead, go to the Shell window (the one that opens when you start IDLE).
  2. Click on Debug -> Debugger. A new "Debug Control" window will pop up. You might see it say [running] for a second and then [inactive]. This is normal. It's waiting for you to start your program.

Step 3: Set a Breakpoint

A breakpoint tells the debugger to pause execution at a specific line. This is where you want to start inspecting things.

  1. Go back to your find_bug.py editor window.
  2. Click on the line where you want to pause. A good place is right at the start of the main() function. Click on line 16: def main():.
  3. To set the breakpoint, press the F12 key. A red dot or block will appear next to the line number. This indicates the breakpoint is set.

Step 4: Run the Debugger

Now, run your script from the Shell window by typing:

>>> exec(open("find_bug.py").read())

(Or, you can go to Run -> Run Module in the editor window, but running from the shell is often clearer when debugging.)

What happens now?

  1. The Debug Control window will change to [running].
  2. The program will execute and immediately pause at your breakpoint (line 16).
  3. The Debug Control window will now show the state. Look at the Locals panel. It should be empty because the main() function hasn't been called yet.

Step 5: Step Through the Code

Now, use the buttons in the Debug Control window to follow the execution.

  1. Press the Go button.

    • The program will run until it hits the next breakpoint or the end. Since there are no more breakpoints, it will run until the first function call inside main().
    • The debugger will now pause at line 19: my_average = find_average(my_scores).
    • Check the Locals panel. You should now see my_scores and my_average (with value None).
  2. Press the Step button.

    • This will execute line 19 and move to the next line, which is line 20: print(f"The average score is: {my_average}").
    • Check the Locals panel again. my_average now has a value! It should be 0. This is correct.
  3. Press Go again.

    • The program will print the first line and continue until it hits the next function call.
    • The debugger will pause at line 25: empty_average = find_average(empty_scores).
  4. Press Step again.

    • This executes line 25 and moves to line 26. empty_average is now None.
  5. Press Go one last time.

    • The program will try to execute the print statement on line 26. To do this, it needs to call find_average(empty_scores) again.
    • This time, the find_average function will run, and when it gets to line 13 (average = total / len(numbers)), it will try to divide by len([]), which is 0.
    • The debugger will catch this error! The Debug Control window will show an exception, and the editor window will highlight the exact line where the error occurred.

You have successfully found the bug! The error happens because len(numbers) is 0 when the list is empty.

Step 6: Fix the Bug and Stop the Debugger

  1. In the editor, fix the bug in the find_average function. A common fix is to check if the list is empty first.

    def find_average(numbers):
        """Calculates the average of a list of numbers."""
        if not numbers:  # Check if the list is empty
            return 0  # Or return None, or raise a custom error
        total = 0
        for num in numbers:
            total = total + num
        average = total / len(numbers)
        return average
  2. To stop the current debugging session, go to the Debug Control window and press the Quit button.

  3. Now you can run your fixed script normally (Run -> Run Module) to see if it works correctly.


Summary of the Debugging Workflow

  1. Write your code and save it.
  2. Start the Debugger: Go to Debug -> Debugger in the Shell.
  3. Set a Breakpoint: Click on a line in your editor and press F12. This is where you want to start inspecting.
  4. Run the Debugger: Execute your script from the Shell using exec(open("your_file.py").read()).
  5. Step Through: Use the Go, Step, Over, and Out buttons to control execution.
  6. Inspect Variables: Watch the Locals panel in the Debug Control window to see variable values change.
  7. Find the Bug: Identify where the logic or values are incorrect.
  8. Quit and Fix: Press Quit in the Debug Control window, fix your code in the editor, and run it again to test.
分享:
扫描分享到社交APP
上一篇
下一篇