Computer Science

Identify the errors from the code below.

def numbers(lst)
    total = 0
    for num in lst:
        if num % 2 == 0:
        total += num
    return total

n = [1, 2, 3, 4, 5, 6]
even_sum = numbers n
print("Sum of even numbers" even_sum)

Python Functions

3 Likes

Answer

(1) Missing colon in function definition.
(2) The line total += num is not properly indented inside the if block.
(3) Missing parentheses around the argument in the function call.
(4) Missing a comma between the string and the variable in the print statement.

Reason — The errors in the code are as follows:

  1. The function definition def numbers(lst) is missing a colon (:) at the end.
  2. The total += num line is not indented correctly, it should be indented inside the if block.
  3. The function call numbers n is missing parentheses around the argument. The correct syntax is numbers(n).
  4. The print() statement is missing a comma between the string and the variable, it should be print("Sum of even numbers", even_sum).

The corrected code is:

def numbers(lst):
    total = 0
    for num in lst:
        if num % 2 == 0:
            total += num
    return total

n = [1, 2, 3, 4, 5, 6]
even_sum = numbers(n)
print("Sum of even numbers", even_sum)

Answered By

3 Likes


Related Questions