…
…
Python Programming Fundamentals · Lesson 12 / 40 · Algorithms and loops
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At the end of the day, Ada has two things: the day's sale amounts and a strip of codes where each order is written as one letter ("LTLCLTW"; L latte, T tea, C cookie, W water). She has four questions: how much revenue was there, how many lattes were sold, which hour was the busiest, and was there any refund? In this lesson you will answer all four with the same idea: walk through the data and accumulate one thing in every iteration.
The first two lines of the end-of-day report you will write by the end of the lesson will look like this (the sales are $4.25, $1.25, $3.75, $4.25, $3.25, and $1.25):
Output6 sales, total $18.00
Average: $3.00In lesson 10 you learned to walk through the characters of a string and the items of a ready-made list one by one with for, and in lesson 11 you learned to end a loop early with break. But in each iteration a loop sees only the current item; while it looks at $4.25, it does not remember the earlier sales. Ada's questions are about the whole day. In this lesson you will learn how to accumulate what the loop sees in a variable. These are the most commonly written loops in programming; once you learn them, you will see the same pattern everywhere, from grade averages to step counters.
In this lesson you will:
Every accumulation loop is written with the same three steps. First: before the loop, start the variable you will accumulate in. Second: inside the loop, update that variable in every iteration. Third: after the loop, on a line with no indentation, use the result once. Each step of this rule has a reason. The start must come before the loop, because every line inside the loop runs again in every iteration. The update must be inside, because each item's contribution is only seen in that item's iteration. The use must come after, because the result is complete only after all the items have been seen.
What programmers call a "pattern" is these three steps, ready-made for frequently asked questions. In this lesson you will see five patterns:
| Pattern | Start | In the loop | Example question |
|---|---|---|---|
| Total | total = 0 | total += value | How much is the daily revenue? |
| Counter | count = 0 | count += 1 (can be conditional) | How many lattes were sold? |
| Largest / smallest | largest = None | Update if larger | Which sale is the most expensive? |
| Flag | found = False | True if the case is seen | Was there any refund? |
| Search | found_at = None | When found, store the position and break |
Putting the start line in the wrong place is the most common mistake. In the code below, the total = 0 line has slipped inside the loop. The sum of 1, 2, and 3 is 6; so what does this code print?
What does this code print?
for n in range(1, 4): total = 0 total += n print(total)
The revenue question asks "how much?"; its pattern is the total. A total starts at 0, because before seeing any sale the revenue is zero. In every iteration, that iteration's amount is added: total += amount is the short form of the total = total + amount line from lesson 2. The pattern for "how many?" is the counter. A counter also starts at 0, but in every iteration it adds 1, not the value. If you keep both together, you can also find the average after the loop: total / count.
Example 1 (case): Total, counter, and average
# 1. Start total = 0 count = 0 # 2. Walk through and accumulate for amount in [4.25, 1.25, 3.75, 4.25, 3.25, 1.25]: total += amount count += 1 # 3. Use the result print(f"{count} sales, total ${total:.2f}") print(f"Average: ${total / count:.2f}")
Output6 sales, total $18.00
Average: $3.00The three comment lines in the code show the three steps. In the first iteration amount is 4.25; total goes from 0 to 4.25 and count from 0 to 1. In the second iteration amount is 1.25; total goes up to 5.5 and count to 2. When the sixth iteration ends, total is 18.0 and count is 6. The average line has no indentation, so it runs once after the loop. If you calculated the average inside the loop, a running average up to that point would be calculated in every iteration, producing five useless intermediate results.
Data does not always come written inside the line. You can put the list in a variable and walk through that variable: sales = [4.25, 1.25, 3.75] and then for amount in sales:. We put the list in a box; you will learn to take a single item out of the box and to add items to it in lesson 23. For now we only walk through every item in the box in order.
A counter can be tied to a condition. In the question "how many lattes were sold?", 1 is added not in every iteration but only when the code is L. A string can be walked through too: each character in the code strip stands for one order. The small example below has a loop that counts the t letters in the word "latte". Step through it; notice that the counter box grows only in the iterations where a t is seen.
Run the code line by line: see which line runs next, the variable boxes and the output.
order = "latte" counter = 0 for letter in order: if letter == "t": counter += 1 print(counter)
The same idea does two accumulations at once on Ada's code strip: while counting the lattes it also adds up the revenue. An elif chain adds the right price for each code.
Example 2 (case): Latte count and revenue from the code strip
codes = "LTLCLTW" lattes = 0 revenue = 0 for code in codes: if code == "L": lattes += 1 revenue += 4.25 elif code == "T": revenue += 1.25 elif code == "C": revenue += 2.00 elif code == "W": revenue += 0.75 print("Lattes:", lattes) print(f"Revenue: ${revenue:.2f}")
OutputLattes: 3
Revenue: $18.00lattes is a conditional counter: it grows only in the L iterations. revenue does a total in every iteration, but the value added changes with the code. The strip has three L, two T, one C, and one W: 3 × 4.25 + 2 × 1.25 + 2.00 + 0.75 = 18.00. Two accumulation variables can live side by side in the same loop; each answers its own question.
The condition of a conditional counter can also be a threshold. Below is code that answers "how many sales are above the threshold?" Change the threshold and see how the counter changes.
Change the threshold: how many sales stay above it?
Pick a value; predict the output first, then look.
1threshold = 12count = 03for amount in [4.25, 1.25, 3.75, 4.25, 3.25, 1.25]:4 if amount > threshold:5 count += 16print(f"Above ${threshold:.2f}: {count} sales")
Above $1.00: 6 sales
Faded lines didn't run with this value. The counter grows not in every iteration but only when the condition is true. With a threshold of $1, all six sales are above it; with $4, only the two $4.25 sales are. The condition changes, the pattern stays the same: start at 0, add 1 in the right iterations, then print.
The average has a trap. If the day closes with no sales at all, the list is empty, the loop never runs, and count stays 0. Division by zero is undefined in math; Python stops too:
OutputTraceback (most recent call last):
File "<kod>", line 6, in <module>
print(f"Average: ${total / count:.2f}")
~~~~~~^~~~~~
ZeroDivisionError: division by zeroRead it from the bottom, as in lesson 5: the error type is ZeroDivisionError, and the location is the average line. The fix is to ask before dividing: if count == 0:, write a message instead of the average; otherwise divide. This check is also done after the loop, because the final value of count is known only when the loop is over.
Now it is your turn. In the cell below, Example 1 is ready. (1) Add 6.00 to the list and run it: what is the average now? (2) Make the list [] and run it: which error came up, and on which line? (3) Edit the average line so that if count == 0: it does print("No sales"), and otherwise it prints the average, then try again with the empty list.
Try it now· not graded; doesn't affect progress
In lesson 9 you wrote a plan that finds the cheapest price and tried it with a trace table: "keep the cheapest so far on the side; compare every new price with it; if it is cheaper, replace the one on the side." Now we translate this plan into Python. The key question is the start value: before seeing any price, what is "the cheapest so far"? It is nothing yet. The way to say that is None, which you know from lesson 8. The condition is also two-part accordingly: "if there is no value yet, or this price is cheaper".
Example 3 (case): The cheapest price
cheapest = None for price in [4.25, 1.25, 3.75, 0.75, 2.00]: if cheapest is None or price < cheapest: cheapest = price print("Cheapest:", cheapest)
OutputCheapest: 0.75In the first iteration cheapest is None is true, so the first price (4.25) is taken without a comparison. In the second iteration 1.25 < 4.25 is true; cheapest becomes 1.25. 3.75 is not cheaper, so nothing changes. 0.75 breaks the record. 2.00 does not. When the loop ends, 0.75 is left on the side. Remember also that or works from left to right: in the first iteration the left side is true, so the comparison price < None is never made, and no error appears.
Starting with 0 instead of None looks reasonable, because the total and the counter started at 0. Predict what the code below will print.
What does this code print?
cheapest = 0 for price in [4.25, 1.25, 3.75, 0.75, 2.00]: if price < cheapest: cheapest = price print(cheapest)
For the largest, the situation is a bit different. If the values are all positive (like sale amounts), starting the largest at 0 works: the first positive value already beats 0. For the smallest, though, 0 is never safe. If you are not sure, start with None in both; it always works.
Ada's third question is "which hour was the busiest?" and here there is something new. The max function you met in lesson 5 gives 28 for max(6, 17, 28), but it does not tell you which hour the 28 belongs to. Finding the value does not answer the "which one" question. For that you keep a second variable and update it inside the SAME if: whenever the record is broken, the current hour is saved too. To know the hour you also need a position counter. The position counter grows in every iteration, so it sits OUTSIDE the if, in the body of the for.
Example 4 (case): The busiest hour
hour = 9 top_sales = 0 busiest_hour = None for sales in [6, 17, 28, 20, 15]: if sales > top_sales: top_sales = sales busiest_hour = hour hour += 1 print(f"Busiest hour: {busiest_hour}:00 (${top_sales:.2f})")
OutputBusiest hour: 11:00 ($28.00)The café opens at 9; each number in the list is one hour's sales. The first iteration stands for 9:00, the second for 10:00. Step through the code below. Look at the three variables separately: hour grows in every iteration, while top_sales and busiest_hour change only in the iterations where a record is broken (6, 17, 28). Since 20 and 15 do not break the record, the if block is skipped in those iterations, but hour += 1 still runs.
Run the code line by line: see which line runs next, the variable boxes and the output.
hour = 9 top_sales = 0 busiest_hour = None for sales in [6, 17, 28, 20, 15]: if sales > top_sales: top_sales = sales busiest_hour = hour hour += 1 print(f"Busiest hour: {busiest_hour}:00 (${top_sales:.2f})")
Because we used > in the condition, if two hours have the same record, the first hour stays: a tie does not break the record. If you want the last hour, you write >=. This small decision is the answer to the question "which one in a tie?"; ask yourself before writing.
Ada's last question is "was there any refund?" At the register, a refund appears as a negative amount. This question wants not a number but a yes or no, and the answer is settled by seeing a single negative amount. The pattern for this is the flag: a variable that starts as False and becomes True when the case you are looking for is seen. A flag that has been raised once is never lowered again; later amounts being positive does not mean no refund was made.
Since seeing it once settles the answer, there is no need to look at the remaining amounts: break from lesson 11 ends the loop right there.
Example 5 (case): Was there any refund?
refund_found = False for amount in [4.25, 2.00, -1.25, 3.00]: if amount < 0: refund_found = True break print("Refund made?", refund_found)
OutputRefund made? TrueThe loop does not touch the flag at 4.25 and 2.00. At -1.25 the flag goes up and break ends the loop; 3.00 is never looked at. If refund_found were still False after the loop, you would know there was no negative amount in the list. Below, put these six lines in the right order with their indentation. Pay special attention to where the break is indented.
Put the lines of Example 5 in the right order with their indentation.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
It may seem logical to "recalculate the flag in every iteration": True if the amount is negative, False if not. Predict the result of the code below; notice that there is a refund in the list.
What does this code print?
refund_found = False for amount in [4.25, -1.25, 3.00]: if amount < 0: refund_found = True else: refund_found = False print(refund_found)
One step beyond the flag is the search. If you ask "which order is the cookie in?" instead of "is there a cookie?", the answer is not yes or no but a position number. For this you keep two variables: a position counter that grows by 1 in every iteration and found_at, which starts as None. When the item you are looking for is seen, the position is written into found_at and the loop exits with break. If found_at is still None after the loop, the item is not there at all. This method of scanning a list one item at a time from start to end is called linear search.
Example 6 (case): Which position is the cookie in?
position = 0 found_at = None for item in ["tea", "latte", "water", "cookie", "latte"]: position += 1 if item == "cookie": found_at = position break print("Cookie position:", found_at)
OutputCookie position: 4Notice that the position += 1 line comes before the if: the position is updated before the comparison, so the first order counts as position 1. Thanks to break, the second latte and what follows are never looked at; the search stops at the first match. If there were no cookie in the list, the output would be Cookie position: None; after the loop you can catch this with if found_at is None: and print "not there at all".
One note: to ask whether a single letter is in the code strip at all, the in from lesson 6 is enough; "C" in "LTLCLTW" gives True directly. The flag and search patterns become necessary when the condition gets more complex ("was there a refund above $4?") or when you need the position.
Now you have five patterns, and the real skill is choosing the right one. The words of the question show you the way. "How much?" wants a total. "How many?" wants a counter. "The most, the least, the most expensive?" wants a largest or smallest; if "which one" is also in the question, add a second variable. "Did it ever …?" wants a flag. "Which position?" wants a search. First read the question with these words, then write the three steps of the pattern.
Which pattern answers each question?
For each row, pick its match from the list, then check.
Real reports do not ask just one question. The good news: several patterns can live side by side in the same loop. The start of each one stands before the loop, its update inside, and its use after. The example below is from outside the café: a teacher wants to learn four things from exam grades.
Example 7 (outside the case): Class grade report
total = 0 count = 0 passed = 0 highest = None perfect_score = False for score in [72, 85, 90, 48, 66]: total += score count += 1 if score >= 50: passed += 1 if highest is None or score > highest: highest = score if score == 100: perfect_score = True print(f"Average: {total / count:.2f}") print("Passed:", passed) print("Highest:", highest) print("Perfect score?", perfect_score)
OutputAverage: 72.20
Passed: 4
Highest: 90
Perfect score? FalseThere are five accumulation variables, and the lines of each fit its pattern: total and count hold the average, passed the conditional counter, highest the largest, and perfect_score the flag. In this example we did not use break with the flag, because the loop has other jobs too; if we broke the loop, the total and the counter would be left half done. If several patterns are in the same loop, think twice before writing break.
Now it is your turn. In the cell below, Example 7 is ready. (1) Add 100 to the list and run it: which lines changed, and which stayed the same? (2) Add the fifth pattern that finds the lowest grade (lowest, starting with None). (3) Add a search that finds the position of the first grade below 50; this time you cannot use break, why?
Try it now· not graded; doesn't affect progress
Ada's end-of-day report is in a single loop: net revenue (total), number of transactions (counter), the largest sale (largest, with None), and refunds (flag). Since the loop does other jobs too, there is no break on the flag.
# End-of-day report: four questions in one loop total = 0 count = 0 largest = None refund_found = False for amount in [4.25, 1.25, -1.25, 3.75, 4.25, 3.25, 1.25]: total += amount count += 1 if largest is None or amount > largest: largest = amount if amount < 0: refund_found = True print(f"{count} transactions, net revenue ${total:.2f}") print(f"Largest sale: ${largest:.2f}") if refund_found: print("A refund was made today") else: print("No refunds today")
Output7 transactions, net revenue $16.75
Largest sale: $4.25
A refund was made todayThere are two $4.25 amounts; because > is used, the first $4.25 stays as the record, and the second does not change it. The -1.25 lowers the net revenue and raises the flag.
Starting the smallest at 0. If you start with cheapest = 0 and compare with if price < cheapest:, all prices are greater than 0, so the condition is never true and the program prints 0. No error message appears; the result is silently wrong. The right way: start with cheapest = None and make the condition if cheapest is None or price < cheapest:.
Printing the result inside the loop. If the print line is indented into the loop body, every iteration's intermediate result is dumped on the screen:
total = 0 for amount in [4.25, 1.25, 3.75]: total += amount print("Total:", total)
OutputTotal: 4.25
Total: 5.5
Total: 9.25Only the last line was wanted. If you delete the indentation of print and bring it level with for, Total: 9.25 is printed once after the loop (the body-versus-after-the-loop distinction from lesson 10).
if count == 0:.None, and update the second variable for "which one" inside the same if; once raised, a flag is not lowered, and a search stops with break when it finds the item.Next lesson: so far we have walked through a single sequence; for two-dimensional tables like table × product, we will write a loop inside a loop (advanced lesson), and in the unit task you will build a number-guessing game.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
The daily step counts of one week: the number of days the goal (8000) was reached is found with a conditional counter, and the best day with the largest + second variable. The position counter (day) grows at the start of every iteration.
goal = 8000 day = 0 reached = 0 best = None best_day = None for steps in [6500, 9200, 8000, 11400, 3000, 10100, 7600]: day += 1 if steps >= goal: reached += 1 if best is None or steps > best: best = steps best_day = day print(f"Days the goal was reached: {reached}") print(f"Best day: day {best_day} ({best} steps)")
OutputDays the goal was reached: 4
Best day: day 4 (11400 steps)Because >= is used, day 3, with exactly 8000 steps, also counts as reaching the goal.