8. Add up a list
Write a function total(numbers) that takes a list of numbers and returns their sum. Don't use Python's sum():
add them up yourself with a loop.
The numbers can be negative or decimals. If the list is empty, there is nothing to add: return 0.
Example 1
Input
numbers = [1, 2, 3, 4]Output
10Explanation1 + 2 + 3 + 4 = 10.
Example 2
Input
numbers = [10, -3]Output
7Explanation10 + (-3) = 7.
Example 3
Input
numbers = []Output
0ExplanationAn empty list adds up to 0.
Constraints
numbershas 0 to 100 items.- Each item is a whole number or a decimal from -1000 to 1000.
Submit also runs 4 more tests you can't see.
Practises Lists (lesson 9).
- Make a variable for the running total and set it to
0before the loop. That 0 is also the answer for an empty list. - Inside
for n in numbers:, add each number to it withresult += n. - Return the total after the loop, not inside it, or the function stops after the first number.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def total(numbers):
"""Add up a list of numbers, without sum().
numbers: list of int or float; may be empty
Returns: int or float, their sum (0 for an empty list)
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.