Menu
Coddy logo textTech

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: 15

In 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: 25

In this case, the sum() function starts with the value 10 and adds all elements from the numbers list to it.

challenge icon

Challenge

Easy

Write 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: 15

Using a starting value:

numbers = [1, 2, 3, 4, 5]
total = sum(numbers, 10)
print(total)
# Output: 25

Try it yourself

sales = eval(input())
starting_cash = eval(input())

# Write code here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow