NEW
Font size
WorksheetsPyhton Debugging Questions
Total questions: 25
Worksheet time: 19mins
1. What will the following code output?
x = 10
print(x) # Print the current value of x
x += 1 # Increment x
# if you wanted to replicate the post increment behavior exactly in python
# you would do the following.
x2 = 10
print(x2)
x2 = x2 + 1
11
10
Compilation error
Runtime error
What will this code print?
a = 10
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("Error")
Error
Infinity
0
1
What is the output of this code?
a = 7
b = 3
print(a % b)
2
1
0
3
What will be the output of the following Python program?
try:
x = 5/0 except Zero DivisionError:
print("Error: Division by zero is not allowed.")
5
0
Error: Division by zero is not allowed.
None
What will be the output of the following Python program?
try:
x = [1, 2, 3] print(x[5]) except IndexError:
print("Error: Index out of range.")
1
2
3
Error: Index out of range.
What will be the output of the following Python program?
try: x = "hello" print(x[10]) except IndexError:
print("Error: Index out of range.")
'h'
'o'
Error: Index out of range.
None
What will be the output of the following Python program?
try:
x = 5
y = "hello"
print(x + y)
except TypeError:
print("Error: Invalid data type.")
5hello
hello5
Error: Invalid data type.
None
What will be the output of the following Python program?
try: x = [1, 2, 3] print(x[5]) except Exception as e print(f"Error: {e}")
1
2
3
Error: list index out of range
What error occurs in this function that uses a variable before assignment?
python
def calculate():
result = num + 10
num = 5
return result
print(calculate())
SyntaxError
UnboundLocalError
NameError
ValueError
What happens when this code runs?
python
text = "hello"
print(text[5])
Prints nothing
Prints a space
IndexError: string index out of range
Prints "o"
What's wrong with this class inheritance?
python
class Animal:
def speak(self):
return "Generic animal sound"
class Dog(Animal):
def bark(self):
return "Woof!"
class Cat(Dog, Animal):
def meow(self):
return "Meow!"
Dog should not inherit from Animal
The class hierarchy is circular
Methods are defined incorrectly
Cat cannot inherit from both Dog and Animal
What will this code print?
python
numbers = [1, 2, 3, 4, 5]
print(numbers[5:])
[5]
[ ]
Error: index out of range
[1, 2, 3, 4, 5]
What's the issue with this function to accumulate values?
python
def sum_values(*args, total=0):
for value in args:
total += value
return total
*args should come after keyword arguments
The function should take a list instead of *args
Cannot use default parameters with *args
The addition operation is incorrect for arbitrary types
What's wrong with this code that tries to delete dictionary items while iterating?
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
if key == 'b':
del my_dict[key]
The if condition syntax is wrong
KeyError: 'b' not found
Cannot delete items from a dictionary
RuntimeError: dictionary changed size during iteration
What happens when executing this code?
python
def process_list(items=None):
if items is None:
items = []
items.append('item')
return items
print(process_list())
print(process_list())
['item'], ['item']
['item'], ['item', 'item']
['item'], []
Error
The datetime module doesn't exist
datetime.now() is not a valid method
'now()' should be called on datetime.datetime, not on datetime
The import statement is incomplete
What's the output of this code involving variable scope?
python
x = 10
def func():
print(x)
x = 5
func()
5
10
UnBoundError
NameError
What's the issue with this list comprehension?
python
result = [x for x in range(10) if x % 2 == 0 else x % 3 == 0]
Cannot mix filter conditions with if-else
The else clause is missing a condition
The range() function is used incorrectly
The comparison operations are invalid
What's the bug in this recursive function?
python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(0))
No base case for n=0
Incorrect multiplication logic
Should use iteration instead of recursion
The function will never terminate
What will happen when this code runs?
python
names = ['Alice', 'Bob', 'Charlie']
for i, name in enumerate(names):
if name.startswith('C'):
del names[i]
print(names)
Will raise an IndexError
Will print ['Alice', 'Charlie']
Will cause an infinite loop
Will print ['Alice', 'Bob']
What's wrong with this code that tries to find the largest number in a list?
python
def find_max(numbers):
max = 0
for num in numbers:
if num > max:
max = num
return max
print(find_max([-5, -10, -3]))
The loop will never execute
The initial value of max should be numbers[0]
The comparison operator should be >=
The function incorrectly handles negative numbers
What's the bug in this code?
python
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total/len(numbers)
print(calculate_average([]))
Missing return statement
Incorrect loop implementation
Division by zero error
Type error in addition
What's wrong with this dictionary comprehension?
python
squares = {x: x*x for x in range(5), 'a': 'b'}
Syntax error in the comprehension structure
Cannot mix integer keys with string keys
The range() function is used incorrectly
Cannot have separate expressions in a dict comprehension
What will this code print?
python
def append_to(element, to=[]):
to.append(element)
return to
print(append_to(1))
print(append_to(2))
print(append_to(3))
[1], [2], [3]
[1], [1, 2], [1, 2, 3]
[1], [2], [1, 2, 3]
Error
Which of these will correctly check if a key exists in a dictionary?
python
my_dict = {'a': 1, 'b': 2}
if my_dict['c']:
if 'c' in my_dict.keys():
if my_dict.has_key('c'):
if 'c' in my_dict:
