pythonbeginner10 minutes
Refactor Messy Code to Improve Readability and Maintainability
You are given a Python function that calculates the sum of even numbers from a list. The current implementation works correctly but is hard to read and maintain. Your task is to refactor the code to make it cleaner and more Pythonic while keeping the behavior the same.
Challenge prompt
Refactor the given function to improve readability and maintainability. Make sure the function still returns the sum of all even numbers from the list it receives as input.
Guidance
- • Use meaningful variable names to improve clarity.
- • Consider using Python's built-in functions or list comprehensions to simplify the logic.
- • Avoid unnecessary code or variables.
- • Make sure the function still works correctly for an empty list or list with no even numbers.
Hints
- • Try using a list comprehension to filter even numbers from the list.
- • The sum() function can add all numbers in a list or iterable.
- • Remember to use the modulus operator (%) to check if a number is even.
Starter code
def sum_even_numbers(numbers):
result = 0
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
result += numbers[i]
return resultExpected output
For input [1, 2, 3, 4, 5, 6], the function should return 12.
Core concepts
functionsloopsconditionalslist comprehensionscode readability
Challenge a Friend
Send this duel to someone else and see if they can solve it.