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
2 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
1 Like
Related Questions
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#
Assertion (A): Positional arguments in Python functions must be passed in the exact order in which they are defined in the function signature.
Reasoning (R): This is because Python functions automatically assign default values to positional arguments.
- Both A and R are true, and R is the correct explanation of A.
- Both A and R are true, and R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
State whether the following statement is True or False:
The
finallyblock in Python is executed only if no exception occurs in the try block.