0% found this document useful (0 votes)
2 views4 pages

Python Debugging Medium Hard

The document contains a series of medium and hard level Python debugging questions along with their respective errors and fixes. It addresses common issues such as logical errors, mutable default arguments, file handling, exception handling, and multithreading problems. Each question provides a brief explanation of the error and a suggested correction to improve code functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Python Debugging Medium Hard

The document contains a series of medium and hard level Python debugging questions along with their respective errors and fixes. It addresses common issues such as logical errors, mutable default arguments, file handling, exception handling, and multithreading problems. Each question provides a brief explanation of the error and a suggested correction to improve code functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Debugging Questions - Medium & Hard

Level

Medium Level Debugging Questions


1. Logical Error in Function
def calculate_area(length, breadth):
area = length + breadth
return area

print(calculate_area(5, 3))
Answer: Area formula is incorrect. Correct Code: area = length * breadth

2. Mutable Default Argument


def add_item(item, lst=[]):
[Link](item)
return lst

print(add_item(1))
print(add_item(2))
Answer: Default mutable list retains values. Fix: def add_item(item, lst=None): if lst is
None: lst = []

3. File Handling Error


file = open("[Link]", "r")
content = [Link]()
print(content)
Answer: File not closed properly. Fix: with open("[Link]", "r") as file: content =
[Link]()

4. Incorrect Exception Handling


try:
num = int("abc")
except:
print("Error")
Answer: Use specific exception. except ValueError:

5. Dictionary Key Error


data = {"name": "John"}
print(data["age"])
Answer: Key does not exist. Fix: print([Link]("age", "Not Found"))

6. Recursion Without Base Case


def factorial(n):
return n * factorial(n-1)
print(factorial(5))
Answer: Missing base case. Fix: if n == 0: return 1

7. Incorrect List Copy


list1 = [1,2,3]
list2 = list1
[Link](4)
print(list1)
Answer: Both refer same list. Fix: list2 = [Link]()

8. Generator Misuse
gen = (i for i in range(3))
print(list(gen))
print(list(gen))
Answer: Generator exhausted after first use.

9. Wrong Lambda Usage


square = lambda x: x^2
print(square(4))
Answer: ^ is XOR not power. Fix: x**2

10. Sorting Without Assignment


nums = [3,1,2]
sorted(nums)
print(nums)
Answer: sorted() returns new list. Fix: nums = sorted(nums)

Hard Level Debugging Questions


1. Multithreading Issue
import threading

counter = 0

def increment():
global counter
for _ in range(100000):
counter += 1

t1 = [Link](target=increment)
t2 = [Link](target=increment)
[Link](); [Link]()
[Link](); [Link]()
print(counter)
Answer: Race condition occurs. Fix using [Link]().

2. Deep vs Shallow Copy


import copy
a = [[1,2],[3,4]]
b = [Link](a)
b[0][0] = 99
print(a)
Answer: Shallow copy affects nested list. Fix: [Link](a)

3. Circular Import Problem


# [Link]
import file2

# [Link]
import file1
Answer: Causes circular dependency. Fix by restructuring imports.

4. Memory Leak with Large List


def create_list():
big = [i for i in range(10**7)]
return big
Answer: High memory usage. Fix using generator expression.

5. Decorator Without *args


def decorator(func):
def wrapper():
print("Before")
func()
return wrapper
Answer: Fails if function has arguments. Fix: def wrapper(*args, **kwargs):

6. Infinite Recursion in Class


class A:
def __init__(self):
self.a = A()
Answer: Creates infinite objects. Fix by removing recursive initialization.

7. Async Without Await


import asyncio

async def main():


print("Hello")

main()
Answer: Coroutine not awaited. Fix: [Link](main())

8. Incorrect __str__ Method


class Person:
def __str__(self):
print("Person")
Answer: __str__ must return string. Fix: return "Person"

9. SQL Injection Risk


query = "SELECT * FROM users WHERE name = '" + user_input + "'"
Answer: Unsafe query construction. Fix using parameterized queries.

10. Deadlock Scenario


Thread1 locks A then B
Thread2 locks B then A
Answer: Deadlock occurs. Fix by consistent lock ordering.

You might also like