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:
- 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)
Answered By
2 Likes
Related Questions
The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.
def swap_first_last(tup) if len(tup) < 2: return tup new_tup = (tup[-1],) + tup[1:-1] + (tup[0]) return new_tup result = swap_first_last((1, 2, 3, 4)) print("Swapped tuple: " result)What will be the output of the following code ?
c = 10 def add(): global c c = c + 2 print(c, end = '#') add() c = 15 print(c, end = '%')- 12%15#
- 15#12%
- 12#15%
- 12%15#