KAHIBARO Bookshelves
Discord Login Register

11.5. Debugging strategies

What “Debugging” Really Means in Practice

Debugging is the process of finding and fixing the cause of a problem (a bug) in your code. In this chapter, you’ll focus on how to do that effectively.

You already know that errors happen and that Python shows error messages. Debugging strategies are about what you actually do once you notice something is wrong—whether it’s an error message or just wrong behavior.

This chapter is practical: step‑by‑step methods, habits, and tools you can use every day.


1. Start With a Clear Problem Statement

Before you dive into the code, be very clear:

  • What is the program supposed to do?
  • What is it actually doing?
  • When exactly does it go wrong?

Write this down in plain language. For example:

  • “The program should ask for two numbers and print their sum, but it crashes when I enter a decimal number.”
  • “The loop should run 10 times but it runs forever.”

Having a clear “expected vs actual” description stops you from randomly changing code.


2. Reproduce the Bug Consistently

You can’t fix what you can’t reproduce.

  • Try to find input that always causes the problem.
  • Note the exact steps that lead to the bug.

Examples:

  • “The program only crashes when the input is empty.”
  • “The bug only appears when I type letters instead of numbers.”

Once you have steps to reliably trigger the bug, debugging becomes much easier.


3. Read Error Messages Systematically

Error messages were introduced earlier; here’s a simple strategy to use them:

  1. Look at the last line of the error.
    • It tells you the error type (like ValueError, IndexError).
  2. Look at the line number and file name just above.
  3. Read the short description on the last line in plain language.

Example:

ValueError: invalid literal for int() with base 10: 'abc'

Strategy:

  • Error type: ValueError → wrong value type for an operation.
  • Description: Python tried to turn 'abc' into an integer, which is impossible.
  • Go to the line number mentioned and check where int() is used.

Don’t just skim error messages; treat them as clues.


4. Add Temporary Print Statements

One of the simplest and most powerful debugging tools is print().

You can:

  • Check the value of variables at different points.
  • See which parts of code are actually being executed.
  • Verify assumptions (“I think this variable is always positive”).

Example:

age = input("Enter your age: ")
print("DEBUG: raw age input =", age)  # temporary debug print
age_num = int(age)
print("DEBUG: converted age =", age_num)

Use these to answer:

  • What is the variable right before the crash?
  • Is the code taking the path you expect (inside if, inside a loop, etc.)?

When you’re done, delete or comment out debugging prints.


5. Debugging by Simplifying (Narrowing Down)

If your program is long, don’t try to fix everything at once. Instead, isolate the problem.

Strategies:

  1. Comment out large sections of code.
    • Run only a small part at a time.
    • If the bug disappears, the problem is in the commented-out part.
  2. Replace complex code with a simpler version to test ideas.

Example: If a long function is failing:

def calculate_bill(items):
    # Temporarily simplify to see if the problem is inside this function
    print("DEBUG: calculate_bill called with:", items)
    return 0  # placeholder

If the program runs without crashing now, the issue is inside your original function body.


6. Check One Change at a Time

When debugging, change only one thing and then run your code again.

  • If you make many changes at once, you won’t know which one fixed (or broke) something.
  • After each change:
    • Run the code.
    • See if the behavior changed.
    • Keep or undo that change.

Think of it like a science experiment: one variable at a time.


7. Compare With a Smaller Example

If something is confusing, create a tiny, separate script that only tests the idea you’re unsure about.

Examples:

  • Unsure how division works? Create a new file test_division.py:
  print(5 / 2)
  print(5 // 2)
  • Confused about if logic? Make a small script with only that if block.

This “toy example” approach helps you understand behavior without distractions.


8. Trace the Code Step by Step (Mentally or on Paper)

Walk through the code line by line as if you were the computer.

For each line:

  • What are the variable values before this line?
  • What changes after this line?
  • Which branch of if is taken?
  • Does the loop run again?

You can do this:

  • In your head (for small code).
  • On paper, writing variable names in a table:

Example:

Code:

x = 0
for i in range(3):
    x = x + i

Trace table:

Stepix beforex after
1000
2101
3213

If the table doesn’t match what your program prints, you’ve found a misunderstanding.


9. Use the Python Debugger (`pdb`) (Gentle Intro)

For more control than print(), you can use the built-in debugger.

Basic use:

  1. Add this line where you want to pause execution:
   import pdb; pdb.set_trace()
  1. Run your script as usual.
  2. When Python hits that line, it stops and gives you a (Pdb) prompt.

At the (Pdb) prompt, you can:

  • Type a variable name to see its value:
    • x
  • Type n (“next”) to run the next line.
  • Type c (“continue”) to run until the next breakpoint or end.

You don’t need to master pdb now, but knowing it exists is useful for stepping through code line by line.


10. Check Inputs and Assumptions

Often, bugs happen because something you assumed is not true.

Ask questions like:

  • “Can this variable be empty?”
  • “Can this value be 0?”
  • “What happens if the user presses Enter without typing anything?”
  • “What if the list is shorter than I expected?”

You can add checks:

if len(numbers) == 0:
    print("DEBUG: numbers list is empty!")

Or:

if age < 0:
    print("DEBUG: negative age detected:", age)

Debugging often means discovering that the real world doesn’t match your assumptions.


11. Use Assertions for Internal Checks

Assertions are a way to say “this must be true here; if not, crash with a clear message.”

Syntax:

assert condition, "Message if condition is False"

Example:

total = sum(prices)
assert total >= 0, "Total price cannot be negative"

If the condition is False, Python raises an AssertionError with your message.

Assertions are especially useful to catch impossible or unexpected states earlier, closer to where they happen.


12. Binary Search Debugging (Divide and Conquer)

For bugs in longer code or data:

  1. Pick the middle point of the code or data.
  2. Add a print() or check there.
  3. See if things are correct up to that point.
  • If it’s correct at the middle, the bug is in the second half.
  • If it’s wrong at the middle, the bug is in the first half.

Repeat:

  • Check the middle of the problematic half.
  • Keep narrowing down until you find the exact line or operation.

This is like searching for a word in a dictionary by always opening in the middle.


13. Read the Code Out Loud (Rubber Duck Debugging)

Explaining your code, even to an object (like a “rubber duck”), often reveals mistakes.

Steps:

  1. Imagine someone knows basic Python but nothing about your code.
  2. Explain:
    • “First, this function does X.”
    • “Then it checks if Y.”
    • “Here I expect Z to happen.”

As you explain, you may notice:

  • “Wait, this condition can never be True.”
  • “I’m saying this variable has the total, but it’s only the last item.”

You can also do this with a friend or classmate.


14. Use Version Control (Even in a Simple Way)

You don’t need advanced tools, but you should avoid losing working code.

Strategies:

  • Make a backup file before big changes:
    • program_v1.py, program_v2.py
  • Or keep a copy of the last working version as:
    • program_working.py

Then:

  • If a change breaks everything and you’re stuck, compare the new version with a working one.
  • See exactly what you changed.

Later, you can learn git, but simple copying is already helpful for beginners.


15. Ask for Help Effectively

When you’re really stuck, asking for help is part of debugging.

When you ask, include:

  1. A short description of what you’re trying to do.
  2. What you expected to happen.
  3. What actually happens (including the full error message).
  4. A small code example that shows the problem (not your whole project if possible).
  5. What you already tried.

Example:

  • “I tried converting user input to int, but I get ValueError when the input is '3.5'. I expected it to accept decimals. Here is the short code that shows the problem: …”

Being clear and specific speeds up getting a useful answer and also often helps you see the bug yourself while preparing the question.


16. Develop a Debugging Mindset

Good programmers are not people who never make mistakes; they are people who debug calmly and systematically.

Key attitudes:

  • Don’t panic: Errors are normal.
  • Be curious: “Why is this happening?” instead of “This is broken.”
  • Be patient: Some bugs take several attempts to find.
  • Be methodical: Use a process, not random changes.

Over time, you will:

  • Learn to recognize patterns (“This looks like an off-by-one bug.”).
  • Make fewer mistakes.
  • Fix them faster when they do happen.

17. A Simple Debugging Checklist

When you face a bug, you can follow this simple checklist:

  1. Can I reproduce the bug every time?
  2. Did I read the full error message and check the line number?
  3. Did I print variable values around the problem area?
  4. Can I simplify or isolate the issue in a smaller script?
  5. Have I made only one change at a time and tested after each?
  6. Did I walk through the code step by step, maybe on paper?
  7. Have I checked my assumptions about inputs and data?
  8. If I’m still stuck, can I prepare a clear question with a small code example?

Using strategies like these will make debugging less frustrating and much more manageable as your programs grow in size and complexity.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms