0% found this document useful (0 votes)
17 views25 pages

Python Debugging Techniques Explained

Chapter 10 covers debugging, defining it as the process of identifying and fixing bugs in programs, which can include syntax, runtime, and semantic errors. It discusses various debugging strategies such as using try/except blocks, assertions, logging, and the Python debugger (pdb) for effective error handling and inspection. The chapter emphasizes best practices for debugging and proactive techniques to avoid bugs in the first place.

Uploaded by

pavithra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views25 pages

Python Debugging Techniques Explained

Chapter 10 covers debugging, defining it as the process of identifying and fixing bugs in programs, which can include syntax, runtime, and semantic errors. It discusses various debugging strategies such as using try/except blocks, assertions, logging, and the Python debugger (pdb) for effective error handling and inspection. The chapter emphasizes best practices for debugging and proactive techniques to avoid bugs in the first place.

Uploaded by

pavithra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Chapter 10 - Debugging

What Is Debugging?
• - A bug is any mistake in a program that causes it to behave incorrectly.
• - Debugging is the process of identifying, tracking down, and fixing bugs.

What Can Go Wrong in Programs?


• Common Types of Bugs:
Dept of MTE 1. Syntax Errors – Code that doesn’t follow the rules of Python.
2. Runtime Errors – Code that crashes during execution (e.g., dividing by zero).
3. Semantic (Logic) Errors – Code that runs but gives wrong results.
Raising Exceptions

Python raises an exception whenever it tries to execute invalid


code.
• Raising an exception is a way of saying, “Stop running the code
in this function and move the program execution to the except
statement.”
• Exceptions are raised with a raise statement. In code, a raise
statement consists of the following:
Dept of MTE
• The raise keyword
• A call to the Exception() function
• A string with a helpful error message passed to the Exception()
function
Raising Exceptions

>>> raise Exception('This is the error message.’)

Traceback (most recent call last):


File "<pyshell#191>", line 1, in <module>
raise Exception('This is the error message.')
Exception: This is the error message.
Dept of MTE
• If there are no try and except statements covering the raise
statement
• that raised the exception, the program simply crashes and
displays the
• exception’s error message.
Example:

def spam(divideBy):
return 42 / divideBy

print(spam(2))
print(spam(12))
print(spam(0)) # Crashes here!
Dept of MTE print(spam(1))

• This program crashes when divideBy is zero. Even though the syntax
is correct, the runtime error stops everything. These kinds of bugs
can be tricky to spot unless we add protection — which leads us to
exception handling.
Raising Exceptions

import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open('[Link]', 'w')
[Link](traceback.format_exc())
Dept of MTE [Link]()
print('The traceback info was written to [Link].')

• The traceback info was written to [Link].


Handling Errors with try and except

• Solution – Use try/except Blocks:


def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
return None
Dept of MTE
# Now call the function
print(spam(2))
print(spam(12))
print(spam(0)) # This will not crash, will print error and return None
print(spam(1))
The try block is where we “try” the risky code. If a ZeroDivisionError happens,
Python jumps to the except block. This way, the program doesn’t crash — it
handles the error gracefully and continues
Debugging Strategies

• Tips for Debugging:

1. Check for typos – Most common issue!


2. Print out variable values – Helps trace what's happening.
3. Use a debugger tool – Step through code line-by-line.
4. Simplify your code – Remove unrelated parts.
Dept of MTE
5. Ask someone else – A fresh set of eyes helps.

• Debugging is often like solving a mystery. These strategies help you


narrow down what’s going wrong and why. It’s often not just about
fixing a bug, but understanding how your program flows.
Assertions – Making Assumptions Explicit

• What is an Assertion?

- An assertion checks if something is true during runtime.


- If it’s not true, Python crashes with an error.

• Syntax:
assert condition, 'Error message'
Dept of MTE
• Example:
assert eggs >= 0, 'Egg count cannot be negative.'

• Explanation:
Assertions are great for debugging during development. They’re like automatic
sanity checks. But they shouldn’t be used for handling user input or controlling
program flow — just to catch bugs early while you're writing the code.
Disabling Assertions

• Did You Know?


- Assertions can be turned off in Python by running with the -O (optimize)
flag:

• python -O [Link]

• Why This Matters:


Dept of MTE - Assertions are for development and testing — not production.
- You shouldn't use them to enforce user input rules or business logic.

• Explanation:
Once your program is working, you might disable assertions for performance.
This is why assertions shouldn’t replace real error handling — they are for
catching bugs, not controlling the program flow
Introducing Logging

Problem:Using print() statements for debugging clutters the output.


Solution:Use the logging module.

How to Set It Up:


import logging
[Link](level=[Link])
[Link]('This is a debug message.')

Dept of MTE
Levels of Logging:
- DEBUG, INFO, WARNING, ERROR, CRITICAL
Explanation:
Logging is like a professional version of print() — it gives you better control, and can
be turned on/off easily. It's perfect for both development and long-term
maintenance.
Review of Logging Levels

Python Logging Levels (from least to most severe):


1. DEBUG: Detailed information for diagnosing problems.
2. INFO: General events (e.g., program start/end).
3. WARNING: Something unexpected happened, but the program can continue.
4. ERROR: A more serious problem; program might not work correctly.
5. CRITICAL: A serious error, program may be unable to continue.

Dept of MTE
Explanation:

• Each level has a specific purpose. Use DEBUG during development, and raise
the level (WARNING, ERROR) in production. Helps filter messages depending on
how much detail you want.
Customizing Logging Format

import logging

[Link](level=[Link],format='%(asctime)s - %
(levelname)s - %(message)s')

Explanation:
- This format shows:
Dept of MTE
- Timestamp
- Severity Level
- Message

Why It Helps:
When debugging complex programs, you can track when errors happen and
what part of the program caused them.
Logging to a File

Save Logs to a File:


[Link](
filename='[Link]',
level=[Link],
format='%(asctime)s - %(levelname)s - %(message)s')

• Explanation:
Dept of MTE
Instead of printing to the console, logs are now saved to a file.
• Useful for:
- Long-running programs
- Scripts running on servers
- Later analysis of issues
Logging Example
import logging
[Link](level=[Link], format=' %(asctime)s - %
(levelname)s - %(message)s')
[Link]('Start of program')
# Define factorial function
def factorial(n):
[Link]('Start of factorial(%s)' % n)
total = 1
Dept of MTE
for i in range(1, n + 1):
total *= i
[Link]('i is %d, total is %d' % (i, total))
[Link]('End of factorial(%s)' % n)
return total
print(factorial(5))
[Link]('End of program')
When to Use Logging vs. Print

Print Statements:
- Quick debugging
- For small test scripts or beginner-level testing

Logging Module:
- For real applications
Dept of MTE - Helps record what happened and when
- More control (levels, output formats, saving to file)

• Explanation:
While print() is okay in a pinch, logging is the professional way. You can
leave logging in your final code — it's a debugging tool and a record-
keeping tool.
• Introduction to the Debugger (pdb)
• What is pdb?
• - Python Debugger (built-in)
• - Lets you pause, step through, and inspect your program
interactively

Dept of MTE • Start it with:
import pdb; pdb.set_trace()

• Explanation:
• The pdb module helps you debug inside the code — like placing a
“breakpoint” in other programming environments. Great for
detailed inspection of variables and logic.
pdb Commands Overview

• Common Commands:
- l (list): Show where you are in the code
- n (next): Go to next line
- s (step): Step into function call
- c (continue): Resume execution
- q (quit): Exit the debugger
Dept of MTE

Explanation:
These commands help you walk through the code interactively. It's
especially useful when you’re not sure which part of the code is failing.
Example with pdb.set_trace()

import pdb

name = 'Alice'
age = 30
pdb.set_trace()
print(f'{name} is {age} years old.')

Dept of MTE
What Happens:
- When Python hits pdb.set_trace(), it pauses.
- You can now inspect name, age, or step through the code.

Explanation:
This lets you test your assumptions about variable values. You can use it
when print() isn’t helping and you need more control over execution flow.
Setting Breakpoints with pdb.set_trace()
• Use Case:
Insert pdb.set_trace() anywhere in the code to pause execution.

Example:
import pdb
a=5
b = 10
pdb.set_trace()
Dept of MTE print(a + b)

Explanation:
When Python hits pdb.set_trace(), the debugger activates.
You can type commands like p, a, b, c, etc. to inspect and resume.
Good for:
- Checking variable values mid-execution.
- Isolating bugs in large scripts.
More pdb Commands

Helpful Commands Recap:


- p expression: Print the result of the expression.
- ! statement: Run a Python statement (e.g., !x = 5)
- a: Print all arguments of the current function.
- b line_number: Set a new breakpoint.
- h or help: List all commands.

Dept of MTE

Explanation:
These tools make pdb powerful. You don’t need an external debugger —
Python gives you control right in the terminal.
Debugging Summary

• Recap of Techniques:
1. Try/Except for handling runtime errors.
2. Assertions for catching logic errors during development.
3. Logging to track events and values.
4. Debugger (pdb) for interactive inspection.

Dept of MTE
Explanation:
Each method has its own use case. In small scripts, print() or assert might be
enough. In large apps, logging and the debugger become essential tools.
Best Practices in Debugging

Tips for Effective Debugging:


- Always read error messages carefully — they give you clues.
- Use print or logging to trace variable values.
- Don’t assume — check your logic.
- Use pdb when you need detailed inspection.
- Clean up your debug code before final release (e.g., remove pdb.set_trace())
Dept of MTE
Explanation:
Debugging is both a technical and a logical skill. These practices help
you become faster and more accurate in solving issues.
Real-Life Debugging Example

A program crashes when calculating average test scores.

scores = [90, 95, 100, 85, 0]


average = sum(scores) / len(scores)

Bug Introduced Later:


scores = []
Dept of MTE
average = sum(scores) / len(scores) # ZeroDivisionError!

Solution:
Use try/except, assert, or input validation to prevent crash:
assert len(scores) > 0, "Score list is empty"

Explanation:
This shows how even small changes can introduce bugs. Defensive
Avoiding Bugs in the First Place

Proactive Tips:
- Write clean, simple code — less room for mistakes.
- Break down problems into small pieces.
- Test as you go — don’t wait until the end.
- Keep variable names meaningful.
Dept of MTE

Explanation:
Most bugs come from complex, messy, or rushed code.
Writing clean and modular code can prevent many
bugs before they happen.
Chapter Summary

Key Concepts Reviewed:


- What bugs are and how to handle them
- try/except blocks for error catching
- Using assert to detect bugs
- Logging for event tracking
- Debugging with pdb
Dept of MTE
- Best practices and proactive techniques

Final Note:
This chapter isn’t just about fixing code — it’s about thinking
clearly when things go wrong and using the right tools to solve
problems.

You might also like