pythonbeginner10 minutes
Fix the Sum Calculation Bug in a List of Numbers
A beginner-level debugging challenge to fix a Python function that is supposed to calculate the sum of a list of numbers but currently returns an incorrect result.
Challenge prompt
The function `calculate_sum` should take a list of numbers and return their total sum. However, the current implementation returns an incorrect value. Identify and fix the bug so the function returns the correct sum.
Guidance
- • Check how the sum is being accumulated inside the loop.
- • Make sure to initialize the sum correctly before the loop.
- • Verify the loop iterates through all elements in the list.
Hints
- • Look at the starting value of the variable that holds the total sum.
- • Check the variable names inside the loop; they might be mutated incorrectly.
- • Confirm that the sum is updated by adding each number, not overwriting it.
Starter code
def calculate_sum(numbers):
total = 0
for num in numbers:
total = num
return totalExpected output
calculate_sum([1, 2, 3, 4, 5]) # Output: 15
Core concepts
loopsvariablesfunctionsbasic debugging
Challenge a Friend
Send this duel to someone else and see if they can solve it.