Using Sum
Part of the Logic & Flow section of Coddy's Python journey — lesson 46 of 78.
The sum() function is a built-in function that allows you to quickly calculate the sum of elements in an iterable, such as a list or a tuple. It provides a concise way to add up numeric values.
Basic Usage:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
# Output: 15In this example, the sum() function calculates the sum of all elements in the numbers list.
Using a Starting Value:
You can also provide a second argument to sum(), which serves as the starting value for the sum. This is useful when you want to add the elements of an iterable to an initial value.
numbers = [1, 2, 3, 4, 5]
total = sum(numbers, 10)
print(total)
# Output: 25In this case, the sum() function starts with the value 10 and adds all elements from the numbers list to it.
Challenge
EasyWrite a program that gets a list of sales amounts and starting cash in the register and calculates the total sales, including the starting cash. Print the result.
Cheat sheet
The sum() function calculates the sum of elements in an iterable like a list or tuple.
Basic usage:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
# Output: 15Using a starting value:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers, 10)
print(total)
# Output: 25Try it yourself
sales = eval(input())
starting_cash = eval(input())
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter