Sum and Average
Now that you can go through a list, let's look at what loops are used for most often. The first pattern adds everything up. Say you have the prices of the things in your shopping cart and want the total:
prices = [120, 45, 300, 85]
total = 0
for price in prices:
total += price
print("Total:", total)Total: 550The variable total collects the sum. It starts at 0, because before you add anything, the sum is zero. In each iteration, total += price adds one price: after the first iteration, total is 120, then 165, 465 and finally 550.
Where each line goes matters:
total = 0goes before the loop, so that it runs only once. Inside the loop, it would settotalback to 0 in every iteration, and at the end,totalwould hold only the last price,85.print()goes after the loop, not indented, when the sum is complete. Indented inside the loop, it would print every partial sum: 120, 165, 465, 550.
The average is the sum divided by the number of values, and the number of values is the length of the list:
average = total / len(prices)
print("Average:", average)Average: 137.5Use len(prices) rather than the number 4. When you add another price to the list, the average will still be right. And remember that / always gives a decimal number: an average of 40 prints as 40.0.
Adding up the numbers in a list is so common that Python has a shortcut for it, the function sum():
prices = [120, 45, 300, 85]
print(sum(prices))550So why learn the loop? Because it can do more than sum(). In a loop, you decide what to add: with an if, for example, only the prices over 100.
One more trap: don't name your variable sum. sum = 0 works, but it hides Python's sum(), and calling sum(prices) later ends with TypeError: 'int' object is not callable. That's why the variable here is called total. The same goes for max, min, len and list.
Instructions
The list reading_minutes holds how many minutes you read on each day of one week. Create a variable total with the value 0. Then go through the list with a for loop and add each value to total with +=.
After the loop, print the sum with print("Total:", total). The output is Total: 280.
At the end of the program, create a variable average with the average: total divided by the length of the list. Print it as Average: 40.0.
Start programming for free
4/11