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)
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:
- The function definition
def numbers(lst)is missing a colon(:)at the end. - The
total += numline is not indented correctly, it should be indented inside theifblock. - The function call
numbers nis missing parentheses around the argument. The correct syntax isnumbers(n). - The
print()statement is missing a comma between the string and the variable, it should beprint("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)