The code given below accepts a list of numbers as an argument and returns the sum of all even numbers from the list. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
def sum_even(lst)
sum=0
for i in range(length(lst)):
if lst[i]%2=0:
sum=sum+lst[i]
return (sum)
Answer:
Answer by student
def
sum_even
(lst)
:
sum=
0
for
i
in
range(
len(lst)
):
if
lst[i]%
2
==
0
:
sum=sum+lst[i]
return (sum)
Detailed answer by teachoo
-lock-
The code given below accepts a list of numbers as an argument and returns the sum of all even numbers from the list. An even number is a number that is divisible by 2, which means it has a remainder of zero when divided by 2. To check if a number is even, we can use the modulo operator (%) which returns the remainder of a division. If the remainder is zero, the number is even, otherwise it is odd. To find the sum of all even numbers in a list, we can use a loop to iterate over each element of the list and check if it is even. If yes, we can add it to a variable that keeps track of the sum. If no, we can skip it and move on to the next element. At the end of the loop, we can return the final sum as the output.
The code has some syntax and logical errors that need to be fixed. Here are the corrections made:
- The function definition should have a colon at the end to indicate the start of the function body. The colon is missing in the original code and should be added after lst.
- The length function does not exist in Python . The correct way to get the length of a list is to use the len function . The original code uses length(lst) and should be replaced with len(lst) .
- The comparison operator for equality in Python is ==, not =. The = operator is used for assignment, not comparison. The original code uses = in the if statement and should be replaced with ==.
- The return statement should be outside the loop, not inside it. The return statement ends the execution of the function and returns a value. If it is inside the loop, it will return after checking only the first element of the list, which is not what we want. We want to check all the elements of the list and then return the final sum. So, the return statement should be moved outside the loop and aligned with the function definition.
So, the corrected code is:
def
sum_even
(lst)
:
#missing colon corrected
sum=
0
for
i
in
range(
len(lst)
): #length function corrected to len
if
lst[i]%
2
==
0
: #comparison operator corrected to ==
sum=sum+lst[i]
return (sum)
#return statement moved outside the loop
-endlock-