wayground logo

Free Printable Worksheets

NEW

Font size

S
M
L
XL
Worksheets

Pyhton Debugging Questions

Total questions: 25

Worksheet time: 19mins

Name
Class
Date
1.

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

a)

11

b)

10

c)

Compilation error

d)

Runtime error

2.

What will this code print?

a = 10

b = 0

try:

print(a / b)

except ZeroDivisionError:

print("Error")

a)

Error

b)

Infinity

c)

0

d)

1

3.

What is the output of this code?

a = 7

b = 3

print(a % b)

a)

2

b)

1

c)

0

d)

3

4.

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.")

a)

5

b)

0

c)

Error: Division by zero is not allowed.

d)

None

5.

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.")

a)

1

b)

2

c)

3

d)

Error: Index out of range.

6.

What will be the output of the following Python program?

try: x = "hello" print(x[10]) except IndexError:

print("Error: Index out of range.")

a)

'h'

b)

'o'

c)

Error: Index out of range.

d)

None

7.

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.")

a)

5hello

b)

hello5

c)

Error: Invalid data type.

d)

None

8.

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}")

a)

1

b)

2

c)

3

d)

Error: list index out of range

9.

What error occurs in this function that uses a variable before assignment?

python

def calculate():

result = num + 10

num = 5

return result

print(calculate())

a)

SyntaxError

b)

UnboundLocalError

c)

NameError

d)

ValueError

10.

What happens when this code runs?

python

text = "hello"

print(text[5])

a)

Prints nothing

b)

Prints a space

c)

IndexError: string index out of range

d)

Prints "o"

11.

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!"

a)

Dog should not inherit from Animal

b)

The class hierarchy is circular

c)

Methods are defined incorrectly

d)

Cat cannot inherit from both Dog and Animal

12.

What will this code print?

python

numbers = [1, 2, 3, 4, 5]

print(numbers[5:])

a)

[5]

b)

[ ]

c)

Error: index out of range

d)

[1, 2, 3, 4, 5]

13.

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

a)

*args should come after keyword arguments

b)

The function should take a list instead of *args

c)

Cannot use default parameters with *args

d)

The addition operation is incorrect for arbitrary types

14.

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]

a)

The if condition syntax is wrong

b)

KeyError: 'b' not found

c)

Cannot delete items from a dictionary

d)

RuntimeError: dictionary changed size during iteration

15.

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())

a)

['item'], ['item']

b)

['item'], ['item', 'item']

c)

['item'], []

d)

Error

16.

Why does this code fail?

python

import datetime

today = datetime.now()

a)

The datetime module doesn't exist

b)

datetime.now() is not a valid method

c)

'now()' should be called on datetime.datetime, not on datetime

d)

The import statement is incomplete

17.

What's the output of this code involving variable scope?

python

x = 10

def func():

print(x)

x = 5

func()

a)

5

b)

10

c)

UnBoundError

d)

NameError

18.

What's the issue with this list comprehension?

python

result = [x for x in range(10) if x % 2 == 0 else x % 3 == 0]

a)

Cannot mix filter conditions with if-else

b)

The else clause is missing a condition

c)

The range() function is used incorrectly

d)

The comparison operations are invalid

19.

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))

a)

No base case for n=0

b)

Incorrect multiplication logic

c)

Should use iteration instead of recursion

d)

The function will never terminate

20.

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)

a)

Will raise an IndexError

b)

Will print ['Alice', 'Charlie']

c)

Will cause an infinite loop

d)

Will print ['Alice', 'Bob']

21.

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]))

a)

The loop will never execute

b)

The initial value of max should be numbers[0]

c)

The comparison operator should be >=

d)

The function incorrectly handles negative numbers

22.

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([]))

a)

Missing return statement

b)

Incorrect loop implementation

c)

Division by zero error

d)

Type error in addition

23.

What's wrong with this dictionary comprehension?

python

squares = {x: x*x for x in range(5), 'a': 'b'}

a)

Syntax error in the comprehension structure

b)

Cannot mix integer keys with string keys

c)

The range() function is used incorrectly

d)

Cannot have separate expressions in a dict comprehension

24.

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))

a)

[1], [2], [3]

b)

[1], [1, 2], [1, 2, 3]

c)

[1], [2], [1, 2, 3]

d)

Error

25.

Which of these will correctly check if a key exists in a dictionary?

python

my_dict = {'a': 1, 'b': 2}

a)

if my_dict['c']:

b)

if 'c' in my_dict.keys():

c)

if my_dict.has_key('c'):

d)

if 'c' in my_dict: