Remember
sum() adds values from an iterable, with an optional starting value. The empty iterable returns that starting value.
sum() adds values from an iterable, with an optional starting value. The empty iterable returns that starting value.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
numbers = range(3)
print(sum(numbers, 10))Top-level scope
range(0, 3)sum() adds values from an iterable, with an optional starting value. The empty iterable returns that starting value.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
numbers = range(3)
print(sum(numbers, 10))
|
v
DISPLAYED RESULT
13
FINAL BINDINGS
numbers --> object 1 (range)
object 1: range(0, 3)Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
numbers = range(3)
print(sum(numbers, 10))Top-level scope
range(0, 3)The example has finished. Compare the final output with the values and references above.
13
What do you expect this program to print?
numbers = range(3)
print(sum(numbers, 10))sum() FunctionThe sum() function in Python returns the total (sum) of all items in an iterable, such as a list or tuple. It’s one of the most frequently used functions in real-world Python programs.
sum(iterable, start=0)
iterable – A sequence like a list, tuple, or set containing numeric values.start – (Optional) The value to start with. Default is 0.start value.numbers = [10, 20, 30]
print(sum(numbers))
60
numbers = [1, 2, 3]
print(sum(numbers, 10))
16
Why? Because 1 + 2 + 3 = 6 and 6 + 10 = 16
values = (5, 15, 25)
print(sum(values))
45
items = [120.5, 250.0, 89.99]
total = sum(items)
print("Total Bill:", total)
Total Bill: 460.49
sum() with non-numeric values like strings or dictionaries will raise a TypeError.''.join() instead.sum() is commonly used in problems that ask for totals, averages, or when working with filter() and map().
sum() adds all elements in an iterable.start value.Write a program that asks the user for 5 numbers and prints their sum.
numbers = []
for i in range(5):
num = float(input("Enter number " + str(i+1) + ": "))
numbers.append(num)
print("Sum =", sum(numbers))
Connect what you noticed in the example with the idea below.
sum() adds values from an iterable, with an optional starting value. The empty iterable returns that starting value.
sum([], 10) returns zero.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.