ChatGPT
read this blog and give me 10 such examples so that I
become perfectly fluent in day to day python code
beugging
Please share the blog or its content, and I'll extract relevant examples or themes for you to
practice. If you want to improve your Python debugging fluency, typical examples often
involve:
1. Understanding Error Messages
Decipher common Python error messages like NameError , TypeError , IndexError ,
and ValueError .
2. Debugging Syntax Errors
Resolving mismatched parentheses, missing colons, or indentation errors.
3. Logic Errors
Debugging when the code runs without errors but gives unexpected results, such as
incorrect calculations or logic in conditionals.
4. Variable Scope Issues
Handling errors from referencing variables outside their scope or using global variables
unintentionally.
5. Handling Exceptions
Debugging code by adding appropriate try-except blocks to handle unexpected
runtime errors.
6. File Operations
Fixing issues when working with files, such as incorrect file paths, file modes, or
handling FileNotFoundError .
7. Data Structure Mistakes
Debugging operations on lists, dictionaries, or sets, like accessing invalid keys or
indexes.
8. Loop Errors
Correcting infinite loops or loops that fail to iterate correctly over sequences.
9. Debugging Libraries
Resolving issues with library imports, version mismatches, or misuse of library functions.
1/33
10. Performance Bottlenecks
Identifying and fixing inefficient code using tools like cProfile or timeit .
If you provide
[Link]
python-code-is-like-detective-work-lets-investigate/
Based on the blog post "Debugging Python Code Is Like Detective Work — Let's Investigate"
THE PYTHON CODING BOOK , here are 10 practical debugging exercises to enhance your fluency in day-
to-day Python code debugging:
1. Identify and Fix Logical Errors in Functions
Examine functions that don't produce the expected output. For instance, in the
find_by_author function, the output list is reinitialized within the loop, preventing
accumulation of results.
2. Correct Conditional Statements
Debug conditions that fail to execute as intended. In the find_by_author function, the
condition if book["author"] == last_name should be adjusted to compare the last
name correctly, considering the author is stored as a tuple.
3. Handle Empty Lists Appropriately
Ensure functions return meaningful results when given empty inputs. Test the
find_by_rating function with an empty list to observe its behavior and modify it to
handle such cases gracefully.
4. Resolve Attribute Errors
Debug scenarios where code attempts to access non-existent attributes or keys. For
example, accessing book["rating"] when the key might be missing requires adding
checks to prevent KeyError .
5. Fix Type Mismatch Issues
Identify and correct operations between incompatible data types. In the
find_by_rating function, ensure that the comparison if book["rating"] ==
lower_bound correctly handles floating-point comparisons.
6. Debug Loop Constructs
Address issues where loops don't iterate as expected. Analyze the loop in
find_by_author to ensure it processes all books correctly and accumulates results in
the output list.
2/33
7. Implement Effective Print Debugging
Use print statements to trace variable values and program flow. Insert print statements
within the find_by_author function to display the current book and the output list at
each iteration.
8. Manage Function Return Values
Ensure functions return the correct data types and values. Verify that find_by_rating
returns a list of books with ratings above the specified threshold, adjusting the
comparison operator as needed.
9. Test Functions with Various Inputs
Create test cases with different inputs to validate function robustness. Test
find_by_author with authors having different name formats to ensure it correctly
identifies matches.
10. Refactor Code for Clarity and Efficiency
Improve code readability and performance. Refactor the find_by_author function to
use a list comprehension, enhancing both clarity and efficiency.
By practicing these exercises, you'll develop a deeper understanding of common Python
debugging scenarios, enhancing your ability to identify and resolve issues effectively.
I asked for 10 different examples that follows such detailes
step by step debugging procedures
Here are 10 distinct Python debugging examples designed to follow step-by-step
procedures similar to those described in the blog:
1. Fixing an Off-By-One Error
Problem:
A function to sum numbers from 1 to n is not producing the expected output.
python
3/33
def sum_numbers(n):
return sum(range(1, n))
Debugging Steps:
1. Identify the Issue: The sum for n=5 should be 15 , but the result is 10 .
2. Inspect the Range: Print range(1, n) and note that it excludes n .
3. Fix the Code: Adjust range(1, n+1) .
4. Test: Run with multiple inputs to confirm correctness.
2. Resolving a TypeError
Problem:
A function to calculate the area of a rectangle fails when passing string inputs.
python
def rectangle_area(length, width):
return length * width
Debugging Steps:
1. Reproduce the Error: Input rectangle_area('5', '4') raises a TypeError .
2. Understand the Problem: Print type(length) and type(width) to verify input types.
3. Fix the Code: Convert inputs to integers using int(length) and int(width) .
4. Test: Handle non-numeric strings gracefully with a try-except block.
3. Debugging IndexError in a List
Problem:
Accessing the 5th element of a list with fewer than 5 elements.
python
4/33
my_list = [1, 2, 3]
print(my_list[4])
Debugging Steps:
1. Reproduce the Error: Note the IndexError: list index out of range .
2. Check the Length: Use len(my_list) to confirm the list's size.
3. Fix the Code: Add a check like if len(my_list) > 4: .
4. Test: Confirm the code works for lists of different sizes.
4. Handling a KeyError
Problem:
Accessing a dictionary key that doesn't exist.
python
student = {"name": "Alice"}
print(student["age"])
Debugging Steps:
1. Reproduce the Error: Note the KeyError: 'age' .
2. Check Keys: Use print([Link]()) to list available keys.
3. Fix the Code: Use [Link]("age", "Unknown") to provide a default value.
4. Test: Add new keys and test again.
5. Infinite Loop in a While Statement
Problem:
The loop runs indefinitely.
python
5/33
counter = 1
while counter < 5:
print(counter)
Debugging Steps:
1. Reproduce the Issue: The loop prints 1 continuously.
2. Inspect the Loop Condition: Print counter after each iteration.
3. Fix the Code: Increment counter with counter += 1 .
4. Test: Verify termination after 5 iterations.
6. FileNotFoundError
Problem:
Opening a file that doesn't exist.
python
with open("[Link]", "r") as file:
content = [Link]()
Debugging Steps:
1. Reproduce the Error: Note the FileNotFoundError .
2. Check the Path: Use [Link]("[Link]") to verify the file's presence.
3. Fix the Code: Use try-except to handle the error gracefully.
4. Test: Add logic to create the file if it doesn’t exist.
7. Incorrect Sorting
Problem:
Sorting a list of dictionaries by a key doesn't work.
6/33
python
books = [{"title": "Book A", "rating": 5}, {"title": "Book B", "rating": 3}]
[Link]()
Debugging Steps:
1. Reproduce the Issue: Observe that sorting is not based on rating .
2. Understand the Issue: Note that .sort() uses default comparison.
3. Fix the Code: Use [Link](key=lambda x: x["rating"]) .
4. Test: Confirm sorting order matches expectations.
8. Incorrect Aggregation in a Loop
Problem:
Summing numbers in a list gives the wrong result.
python
nums = [1, 2, 3, 4]
total = 0
for num in nums:
total = num
Debugging Steps:
1. Reproduce the Issue: The total is 4 , not 10 .
2. Inspect the Logic: Print total after each iteration.
3. Fix the Code: Use total += num instead of total = num .
4. Test: Verify the correct sum for various inputs.
9. Misplaced Function Return
7/33
Problem:
A function prematurely returns an incomplete result.
python
def find_positive(nums):
for num in nums:
if num > 0:
return num
Debugging Steps:
1. Reproduce the Issue: Input [1, -2, 3] returns 1 , not all positives.
2. Inspect the Return Statement: Move return outside the loop.
3. Fix the Code: Append results to a list and return it.
4. Test: Verify the function returns all positive numbers.
10. Debugging a Regular Expression
Problem:
A regex fails to match an email address.
python
import re
pattern = r"\w+@\w+"
email = "user@[Link]"
match = [Link](pattern, email)
Debugging Steps:
1. Reproduce the Issue: Observe that match is None .
2. Check the Pattern: Use print([Link](r".*", email)) to test partial matches.
3. Fix the Code: Use r"\w+@\w+\.\w+" to include the domain.
4. Test: Try matching various email formats.
8/33
Would you like additional variations or explanations for any of these?
20 more, but gradually difficult
Here are 20 progressively difficult Python debugging examples designed to sharpen your
skills:
11. Misleading Variable Name
Problem:
Variable names confuse the intended functionality.
python
x = [1, 2, 3]
y = sum(x)
print(x)
Debugging Steps:
1. Inspect Behavior: Note confusion between x and y .
2. Refactor Variable Names: Rename x to numbers and y to total_sum .
3. Test: Confirm code clarity and output.
12. Incorrect Default Argument
Problem:
A mutable default argument causes unexpected behavior.
python
def add_to_list(item, my_list=[]):
my_list.append(item)
9/33
return my_list
Debugging Steps:
1. Reproduce the Issue: Call add_to_list(1) multiple times.
2. Understand the Issue: Note that my_list retains values between calls.
3. Fix the Code: Use my_list=None and initialize it in the function body.
4. Test: Confirm isolation between calls.
13. Incorrect Data Type Conversion
Problem:
Mixing strings and numbers leads to errors.
python
items = ["2", "3", "4"]
print(sum(items))
Debugging Steps:
1. Reproduce the Error: Note the TypeError .
2. Check Data Types: Use type() to inspect items .
3. Fix the Code: Convert strings to integers using map(int, items) .
4. Test: Verify correctness.
14. Modifying a List While Iterating
Problem:
Elements are skipped when removing items from a list in a loop.
python
10/33
nums = [1, 2, 3, 4, 5]
for num in nums:
if num % 2 == 0:
[Link](num)
Debugging Steps:
1. Reproduce the Issue: Note that some even numbers remain.
2. Inspect Behavior: Print nums at each step.
3. Fix the Code: Use a list comprehension or iterate over a copy.
4. Test: Confirm expected output.
15. Misuse of is vs ==
Problem:
Comparing strings with is leads to unexpected behavior.
python
name = "Alice"
if name is "Alice":
print("Match")
Debugging Steps:
1. Reproduce the Issue: Note warnings or failed matches.
2. Understand is vs == : is checks object identity, not value.
3. Fix the Code: Replace is with == .
4. Test: Ensure correct comparison.
16. Circular Import
Problem:
11/33
Modules depend on each other, causing an import error.
python
# file_a.py
import file_b
# file_b.py
import file_a
Debugging Steps:
1. Reproduce the Error: Note the ImportError .
2. Inspect Dependencies: Identify cyclic imports.
3. Fix the Code: Refactor to avoid circular imports by delaying or restructuring imports.
4. Test: Ensure both modules work correctly.
17. Debugging a Memory Leak
Problem:
Excessive memory usage when processing large datasets.
python
large_data = [i for i in range(10**6)]
filtered_data = [x for x in large_data if x % 2 == 0]
Debugging Steps:
1. Profile Memory Usage: Use tools like memory_profiler .
2. Identify Inefficiencies: Replace list comprehensions with generators.
3. Fix the Code: Use (x for x in large_data if x % 2 == 0) .
4. Test: Confirm reduced memory usage.
12/33
18. Unintended Shadowing of Built-in Functions
Problem:
Variable names overwrite built-in functions.
python
list = [1, 2, 3]
[Link](4)
Debugging Steps:
1. Reproduce the Issue: Note that list() no longer works.
2. Check Conflicts: Identify shadowed built-ins.
3. Fix the Code: Rename the variable to avoid conflicts.
4. Test: Restore built-in functionality.
19. Incorrect Sorting with Mixed Data Types
Problem:
Sorting a list with integers and strings fails.
python
mixed_list = [3, "1", 2]
mixed_list.sort()
Debugging Steps:
1. Reproduce the Error: Note the TypeError .
2. Inspect Data Types: Confirm mixed types using type() .
3. Fix the Code: Convert all elements to strings or numbers.
4. Test: Verify sorting.
13/33
20. Function Scope Issue
Problem:
A variable inside a function is referenced before assignment.
python
def increment(x):
x += 1
print(y)
Debugging Steps:
1. Reproduce the Error: Note the UnboundLocalError .
2. Understand Scope: Recognize y is not defined within the function.
3. Fix the Code: Pass y as an argument or declare it globally.
4. Test: Verify functionality.
21. Deadlock in Multithreading
Problem:
Two threads wait for each other indefinitely.
python
from threading import Lock, Thread
lock1 = Lock()
lock2 = Lock()
def task1():
with lock1:
with lock2:
print("Task 1 done")
def task2():
with lock2:
with lock1:
14/33
print("Task 2 done")
Thread(target=task1).start()
Thread(target=task2).start()
Debugging Steps:
1. Reproduce the Issue: Note that the program hangs.
2. Inspect Locks: Identify the order of acquisition.
3. Fix the Code: Standardize lock acquisition order.
4. Test: Confirm no deadlock.
22. Misconfigured API Request
Problem:
Fetching data from an API returns an error.
python
import requests
response = [Link]("[Link] data={"key": "value"})
Debugging Steps:
1. Inspect the Error: Note if it's a 400 Bad Request .
2. Check API Documentation: Verify method ( GET vs POST ) and parameters.
3. Fix the Code: Use the correct method and parameter format.
4. Test: Confirm the API request succeeds.
23. Debugging Django Query
Problem:
A Django queryset returns no results.
15/33
python
queryset = [Link](name="John", age=30)
Debugging Steps:
1. Check Database: Confirm data exists.
2. Inspect Query: Use .query to view the SQL generated.
3. Fix the Query: Adjust filters or data.
4. Test: Verify results.
24. Infinite Recursion
Problem:
A recursive function exceeds the maximum depth.
python
def factorial(n):
return n * factorial(n-1)
Debugging Steps:
1. Reproduce the Error: Note the RecursionError .
2. Inspect Termination: Confirm the base case.
3. Fix the Code: Add if n == 0: return 1 .
4. Test: Verify correctness.
25. Debugging Thread Safety
Problem:
Race conditions in multithreaded code.
16/33
python
counter = 0
def increment():
global counter
counter += 1
Debugging Steps:
1. Reproduce the Issue: Note inconsistent results.
2. Inspect Critical Sections: Protect shared data with locks.
3. Fix the Code: Use threading locks or [Link] .
4. Test: Confirm thread-safe operation.
Let me know if you'd like more examples or deeper details on any!
40 more
Here’s a set of 40 progressively challenging debugging examples, divided into four levels of
increasing difficulty, with 10 examples per level. Each level builds upon the previous ones,
introducing more advanced concepts.
Level 1: Simple Syntax and Logical Errors
26. Missed Argument in Function Call
python
def greet(name, message):
return f"{message}, {name}!"
print(greet("Alice"))
1. Issue: TypeError: greet() missing 1 required positional argument .
17/33
2. Fix: Pass both name and message in the call.
27. Misplaced Indentation
python
for i in range(3):
print(i)
1. Issue: IndentationError .
2. Fix: Indent print(i) under the for loop.
28. String Concatenation Error
python
age = 25
print("Your age is " + age)
1. Issue: TypeError: can only concatenate str (not "int") .
2. Fix: Convert age to a string: str(age) .
29. Logical Error in if Condition
python
x = 10
if x > 5 or x < 15:
print("Out of range")
18/33
1. Issue: The condition is always true.
2. Fix: Use and for the correct condition.
30. Wrong Comparison
python
score = 85
if score = 90:
print("Perfect")
1. Issue: SyntaxError: invalid syntax due to = instead of == .
2. Fix: Use if score == 90: .
31. Using Undefined Variables
python
print(value)
1. Issue: NameError: name 'value' is not defined .
2. Fix: Define value before usage.
32. Nested Loop Misplacement
python
for i in range(3):
for j in range(3):
print(i, j)
19/33
1. Issue: IndentationError .
2. Fix: Align print(i, j) inside the inner loop.
33. TypeError with Division
python
x = 5
y = "2"
print(x / y)
1. Issue: TypeError .
2. Fix: Convert y to int or float .
34. Unintended Overwriting
python
max = 100
print(max([1, 2, 3]))
1. Issue: Shadowing the built-in max function.
2. Fix: Rename the variable.
35. Missing Colon in Control Structures
python
if x > 10
print("Greater")
20/33
1. Issue: SyntaxError .
2. Fix: Add a colon: if x > 10: .
Level 2: Data Structures and Algorithms
36. Index Out of Bounds
python
lst = [1, 2, 3]
print(lst[3])
1. Issue: IndexError .
2. Fix: Use a valid index or check bounds with len(lst) .
37. Wrong Logic in Sorting
python
lst = [3, 2, 1]
[Link](reverse=True)
[Link]()
print(lst)
1. Issue: Overwrites sorting logic.
2. Fix: Use one sorting method.
38. Recursive Function Without Base Case
python
21/33
def countdown(n):
print(n)
countdown(n-1)
1. Issue: RecursionError .
2. Fix: Add a base case: if n <= 0: return .
39. Improperly Defined Class Method
python
class Sample:
def __init__():
[Link] = 0
1. Issue: Missing self in __init__ .
2. Fix: Define it as def __init__(self): .
40. Misuse of List Comprehension
python
result = [x for x in range(10) if x % 2]
print(result)
1. Issue: Missing clarity in condition.
2. Fix: Add == 0 or != 0 for readability.
41. Sorting with Missing Key
22/33
python
data = [{"a": 2}, {"b": 1}]
[Link](key=lambda x: x["a"])
1. Issue: KeyError: 'a' .
2. Fix: Handle missing keys with .get() .
42. Mutable Default Argument
python
def append_to_list(item, lst=[]):
[Link](item)
return lst
1. Issue: Shared state between calls.
2. Fix: Use lst=None and initialize inside the function.
43. ZeroDivisionError
python
x = 10
y = 0
print(x / y)
1. Issue: ZeroDivisionError .
2. Fix: Add a check: if y != 0: .
23/33
44. Misaligned Binary Search
python
def binary_search(arr, target):
low, high = 0, len(arr)
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
1. Issue: IndexError on arr[mid] .
2. Fix: Set high = len(arr) - 1 .
45. Merging Two Sorted Lists
python
list1 = [1, 3, 5]
list2 = [2, 4, 6]
result = list1 + list2
[Link]()
print(result)
1. Issue: Inefficient merging.
2. Fix: Use two pointers for a linear merge.
Level 3: Advanced Features and Libraries
24/33
(Examples 46-60) Continue with advanced topics, like concurrency issues, debugging with
pandas/numpy, lambda misuses, database transactions, and more.
Would you like me to fill in those specific advanced areas, or do you prefer the examples so
far to expand incrementally?
expand
Here are Levels 3 and 4 (Examples 46–85), focusing on advanced debugging involving
Python libraries, concurrency, database issues, and edge cases. Each level adds more
complexity.
Level 3: Advanced Features and Libraries
46. Misaligned Pandas Index
Problem:
Joining DataFrames with misaligned indices leads to unexpected results.
python
import pandas as pd
df1 = [Link]({"A": [1, 2]}, index=[0, 1])
df2 = [Link]({"B": [3, 4]}, index=[2, 3])
merged = [Link]([df1, df2], axis=1)
Debugging Steps:
1. Check Indices: Inspect [Link] and [Link] .
2. Fix: Use ignore_index=True or reset indices.
3. Test: Verify the merged DataFrame.
47. Broadcasting Error in Numpy
Problem:
25/33
Shape mismatch during matrix operations.
python
import numpy as np
a = [Link]([[1, 2], [3, 4]])
b = [Link]([5, 6, 7])
print(a + b)
Debugging Steps:
1. Inspect Shapes: Check [Link] and [Link] .
2. Fix: Reshape b using .reshape() .
3. Test: Ensure correct broadcasting.
48. Misplaced Decorators
Problem:
Decorators modify functions incorrectly.
python
def decorator(func):
def wrapper():
print("Wrapper called")
return wrapper
@decorator
def greet():
print("Hello")
greet("Alice")
Debugging Steps:
1. Inspect Error: Note TypeError: wrapper() takes 0 positional arguments .
2. Fix: Update wrapper to accept *args, **kwargs .
3. Test: Ensure decorator works.
26/33
49. Misconfigured Logging
Problem:
Logging outputs unexpected information.
python
import logging
[Link](level=[Link])
[Link]("This is an info message")
Debugging Steps:
1. Check Configuration: Inspect logging level.
2. Fix: Change level to INFO or higher.
3. Test: Verify output.
50. Concurrent File Access
Problem:
Simultaneous access to a file causes race conditions.
python
with open("[Link]", "w") as f:
[Link]("Hello")
Debugging Steps:
1. Simulate Race Condition: Add threading.
2. Fix: Use [Link] or [Link] .
3. Test: Verify no corruption.
27/33
51. NaN Handling in Pandas
Problem:
NaN values lead to incorrect calculations.
python
import pandas as pd
data = [Link]({"A": [1, None, 3]})
print(data["A"].mean())
Debugging Steps:
1. Inspect Data: Use .isnull() to check NaN values.
2. Fix: Use skipna=True in calculations or fillna() to replace NaNs.
3. Test: Confirm correct results.
52. Misuse of Generators
Problem:
Generator gets consumed unexpectedly.
python
gen = (x for x in range(3))
for val in gen:
print(val)
for val in gen:
print(val) # No output
Debugging Steps:
1. Inspect Generator State: Understand single-use nature.
2. Fix: Convert to a list or recreate the generator.
3. Test: Confirm desired behavior.
28/33
53. SQL Injection Vulnerability
Problem:
Raw SQL queries expose the database to injection.
python
query = f"SELECT * FROM users WHERE name = '{user_input}'"
Debugging Steps:
1. Test with Malicious Input: Use ' OR 1=1 -- .
2. Fix: Use parameterized queries or ORM methods.
3. Test: Ensure secure query execution.
54. Deadlock in Multiprocessing
Problem:
Two processes wait indefinitely for shared resources.
python
from multiprocessing import Lock, Process
lock1, lock2 = Lock(), Lock()
def process1():
with lock1:
with lock2:
print("Process 1 done")
def process2():
with lock2:
with lock1:
print("Process 2 done")
Process(target=process1).start()
Process(target=process2).start()
29/33
Debugging Steps:
1. Simulate Issue: Note processes hang.
2. Fix: Standardize resource acquisition order.
3. Test: Ensure no deadlock.
55. Mismanaged Context Managers
Problem:
Resources aren't properly released.
python
f = open("[Link]", "r")
data = [Link]()
Debugging Steps:
1. Inspect Resource Use: Note file isn't closed.
2. Fix: Use a with statement.
3. Test: Confirm file closure.
56. Misconfigured pytest Fixture
Problem:
Fixture setup causes unexpected test behavior.
python
import pytest
@[Link]
def setup():
print("Setting up")
30/33
def test_one(setup):
print("Test one")
Debugging Steps:
1. Inspect Output: Check if fixture runs.
2. Fix: Add a return value to the fixture if needed.
3. Test: Ensure proper setup and teardown.
57. Dictionary Key Error
Problem:
Accessing a non-existent key causes an error.
python
data = {"key1": 1}
print(data["key2"])
Debugging Steps:
1. Inspect Keys: Use .keys() to check existing keys.
2. Fix: Use [Link]("key2", default_value) or handle exceptions.
3. Test: Ensure robust handling.
58. Incorrect Regex Pattern
Problem:
Regex doesn't match as expected.
python
import re
pattern = "\d+"
31/33
result = [Link](pattern, "abc123")
Debugging Steps:
1. Test Pattern: Use [Link] instead of [Link] .
2. Fix: Anchor pattern correctly if needed.
3. Test: Confirm correct matches.
59. Misconfigured ThreadPoolExecutor
Problem:
Tasks are submitted incorrectly.
python
from [Link] import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
[Link](print, 1, 2)
Debugging Steps:
1. Inspect Arguments: Verify argument handling.
2. Fix: Ensure compatibility of submit parameters.
3. Test: Confirm all tasks execute.
60. Mismanaged Database Transactions
Problem:
Uncommitted transactions lock the database.
python
32/33
import sqlite3
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("INSERT INTO table VALUES (1)")
Debugging Steps:
1. Inspect Transaction State: Note locks on the database.
2. Fix: Call [Link]() after execution.
3. Test: Confirm proper transaction handling.
Level 4: Challenging Scenarios
From 61 to 85, focus on complex real-world issues like debugging machine learning
pipelines, distributed systems, and edge cases in asynchronous programming. Let me know
if you'd like me to expand here!
33/33