Functions Debugging#

  • Each of the following short code contains one or more bugs.     

  • Please identify and correct these bugs.

  • Provide an explanation for your answer.

Question-1#

def f(x)
  return x**2

Solution

The missing colon in the first line should be added.

Question-2#

def (x,y,z):
  return x+y+z

Solution

The name of the function is missing.

Question-3#

def f(x,y):
  return x+y

print(f(1,2,3))

Solution

The function f has two parameters, but in the last line, three parameters are given.

Question-4#

def func(a,b,c):
  x = a**2+b*4-c
  return x

func(1,5)

Solution

The function func has three parameters (a, b, c). In the last line, only two inputs are provided for the func() function.

Question-5#

def my_func(x):
  return x+6

my_func('3')

Solution

The value ‘3’ is a string, and inside the function, an attempt is made to add 6 to the string ‘3’, resulting in an error.

Question-6#

def my_func(x):
  return str(x)+6

my_func(3)

Solution

str(x) represents a string, while 6 is an integer. They cannot be added or concatenated directly.

Question-7#

def f(x):
  y = 5
  return x+y

print(f(10))
print(y)

Solution

y is a local variable, and it cannot be accessed outside the function, as attempted in the last line.

Question-8#

def f(y=0, x):
  return x+y

Solution

The non-default parameters must be placed before default parameters. The correct form is f(x, y=0).