The code given below accepts a list of numbers as an argument and returns the sum of all even numbers in 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(lst):
if i % 2 = 0:
sum += i
else
continue
return sum
Answer:
Answer by student
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 in the list. It has some syntax and logical errors that need to be corrected.
- The first error is in the for loop . The range() function takes an integer as an argument and returns a sequence of numbers from 0 to that integer minus one. However, the argument given to the function is lst, which is a list of numbers, not an integer. This will cause a TypeError. To fix this error, we need to iterate over the elements of lst directly, not over the range of lst. Therefore, we need to change range(lst) to lst in the for loop.
- The second error is in the if condition . The assignment operator (=) is used to assign a value to a variable, not to compare two values for equality. To compare two values for equality, we need to use the equality operator (==), which returns True if the values are equal and False otherwise. Therefore, we need to change i % 2 = 0 to i % 2 == 0 in the if condition.
- The third and fourth errors are related to indentation and colons . In Python, indentation is used to indicate the block of code that belongs to a certain statement or clause. A colon (:) is used to mark the end of a statement or clause header and the beginning of its block of code. In the given code, the line sum += i is not indented properly under the if condition. Also, there is no colon after the else clause. These errors will cause a SyntaxError or an IndentationError. To fix these errors, we need to indent sum += i and add a colon after else.
- After making these corrections, the code will look like this:
-endlock-