pythonbeginner10 minutes
Refactor Messy Code to Calculate the Sum of Even Numbers
Improve the readability and quality of a Python function that calculates the sum of even numbers from a list, while keeping the output correct.
Challenge prompt
You are given a Python function that accepts a list of integers and returns the sum of all even numbers in the list. The code works correctly but is messy, hard to read, and uses unnecessary steps. Refactor this function to make it clearer, more readable, and more Pythonic while maintaining exactly the same behavior and output.
Guidance
- • Focus on improving variable names, simplifying loops or conditionals.
- • Remove any redundant or unnecessary code.
- • Use built-in Python features or idioms where appropriate.
- • Make sure the function output remains exactly the same for all inputs.
Hints
- • Consider using list comprehensions or generator expressions.
- • Think about using built-in functions like sum() to reduce code lines.
- • Avoid unnecessary temporary variables that don't add clarity.
Starter code
def sum_even_numbers(numbers):
total = 0
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
total = total + numbers[i]
return total
# Example usage:
print(sum_even_numbers([1, 2, 3, 4, 5, 6]))Expected output
12
Core concepts
loopsconditionalsfunctionscode readabilitylist comprehensions
Challenge a Friend
Send this duel to someone else and see if they can solve it.