1# Python code to demonstrate the working of
2# sum()
3numbers = [1,2,3,4,5,1,4,5]
4
5# start parameter is not provided
6Sum = sum(numbers)
7print(Sum) # result is 25
8# start = 10
9Sum = sum(numbers, 10)
10print(Sum) # result is 10 +25 = 35
1# Sum the contents of a list without the builtin sum function
2
3list = [1,2,3,4,5]
4sum = 0
5
6# loop through each position of the list and
7# add the contents of each position to the variable, sum
8for i in range(len(list)):
9 sum += list[i]
10
11# result is 1 + 2 + 3 + 4 + 5 = 15
12print(sum)
1To get the sum of a list in python, you just call the built in sum() function.
2An example:
3
4>>> lst = [3, 7, 1, 9, 4]
5>>> sum(lst)
624
1def calculate_cards(cards):
2 total= 0
3 for card in cards:
4 total = total + card
5 return total
6print(calculate_cards([11,7,5]))