pythonbeginner10 minutes
Fix the Bug in the Sum of Even Numbers Function
A simple Python function is intended to sum all even numbers from a list, but it contains a bug. Your task is to identify and fix the bug so the function returns the correct sum of even numbers.
Challenge prompt
The function sum_even_numbers(nums) is supposed to take a list of integers and return the sum of all even numbers in the list. However, it currently returns the wrong result. Fix the bug in the function so it returns the correct sum.
Guidance
- • Check how the function is checking if a number is even.
- • Ensure the function correctly accumulates the sum of even numbers only.
- • Test the function with different lists to confirm the fix.
Hints
- • Recall that even numbers are divisible by 2 with no remainder.
- • Look carefully at the if condition that checks for even numbers.
Starter code
def sum_even_numbers(nums):
total = 0
for num in nums:
if num % 2 == 1:
total += num
return totalExpected output
sum_even_numbers([1, 2, 3, 4, 5, 6]) should return 12
Core concepts
modulus operatorfor loopsconditional statementsaccumulators
Challenge a Friend
Send this duel to someone else and see if they can solve it.