[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"i-lucide:moon":3,"i-lucide:sun":8,"i-lucide:menu":10,"sample:python-loops":12,"i-lucide:arrow-left":450,"i-lucide:lightbulb":452,"i-lucide:plus":454,"i-lucide:arrow-right":456,"i-lucide:chevron-down":458,"i-lucide:message-circle":460,"i-lucide:swords":462},{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":7},0,24,false,"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":9},"\u003Cg fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\">\u003Ccircle cx=\"12\" cy=\"12\" r=\"4\"\u002F>\u003Cpath d=\"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32l1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41\"\u002F>\u003C\u002Fg>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":11},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M4 5h16M4 12h16M4 19h16\"\u002F>",{"slug":13,"title":14,"summary":15,"discipline_slug":16,"discipline_name":17,"category_slug":18,"estimated_minutes":19,"interactions":20,"version":23,"examples":325},"python-loops","Teaching a computer to count and add up","Many questions about a list of data are answered in the same way: start a variable before a loop, update it once for each item, and read the answer afterwards. This lesson teaches that accumulator pattern for totals, counts and maxima.","computer-science","Computer Science","formal-sciences",30,[21,22],"code_lab","quiz",{"id":24,"lesson_id":25,"version":26,"status":27,"title":14,"summary":15,"objective":28,"estimated_minutes":19,"document":29,"content_hash":320,"published_at":321,"change_note":38,"provenance":322},"afbe825b-3673-417c-910d-324d658f6337","60a986ee-b2d9-4748-b462-86576a8b9857",1,"published","Write a for loop that uses an accumulator variable to compute a total, a count or a maximum over a list.",{"schema_version":26,"title":14,"summary":15,"objective":28,"estimated_minutes":19,"sections":30,"vocabulary":299,"references":319},[31,41,56,72,112,158,241,287],{"kind":32,"title":33,"blocks":34},"goal","What you will be able to do",[35],{"id":36,"depth":37,"emphasis":38,"type":39,"markdown":40},"goal-outcomes","core",null,"rich_text","By the end of this lesson you will be able to:\n\n- explain what an *accumulator* is and where its three parts go: before the loop, inside it and after it,\n- write a `for` loop that adds up the numbers in a list,\n- adapt the same loop to count the items that pass a test and to find the largest item,\n- spot the common mistakes that make an accumulator loop give the wrong answer.",{"kind":42,"title":43,"blocks":44},"why","Why it matters",[45,49],{"id":46,"depth":47,"emphasis":38,"type":39,"markdown":48},"why-matters","standard","Programs spend much of their time answering questions about collections of things. *What do these orders add up to? How many students passed? Which day was the hottest?* Each question boils a whole list down to a single value, and each is answered with the same small pattern: one variable that is updated as the loop visits each item.\n\nOnce you can see the pattern you will find it everywhere, including in tools that hide the loop from you. A spreadsheet's SUM, COUNTIF and MAX, and a database query that totals a column, all do what you are about to write by hand.",{"id":50,"depth":47,"emphasis":51,"type":52,"tone":53,"title":54,"markdown":55},"why-builtins","practical","callout","note","Python can already do this","Python has the built-in functions `sum()`, `len()`, `max()` and `min()`, and in everyday code you should use them. The reason to write the loop yourself is that real questions rarely fit the built-ins exactly. *The total of the orders over 50. The longest word that starts with a vowel. The balance after each transaction.* As soon as there is a condition or a twist you need the pattern itself, and you need to know it well enough to bend it.",{"kind":57,"title":58,"blocks":59},"recall","What this builds on",[60,63],{"id":61,"depth":47,"emphasis":38,"type":39,"markdown":62},"recall-prerequisites","This lesson assumes you have met four pieces of Python.\n\n- **Assignment.** `x = 5` stores 5 under the name `x`. The right-hand side is worked out first, so `x = x + 1` means: take the current value of `x`, add 1, and store the result back under the same name.\n- **Lists.** `prices = [4, 7, 1]` holds three numbers in order. `prices[0]` is the first item, and `len(prices)` is the number of items.\n- **The for loop.** `for price in prices:` runs the indented lines below it once for each item, with `price` set to each item in turn. Lines that are not indented under the `for` run only after the loop has finished.\n- **Conditions and functions.** `if price > 5:` runs its indented lines only when the test is true. `def name(parameter):` defines a function, and `return` hands a value back to whoever called it.",{"id":64,"depth":47,"emphasis":38,"type":22,"kind":65,"prompt":66,"options":67,"numeric":68,"hint":70,"explanation":71},"recall-assignment","numeric","Quick recall: three lines run in order: `x = 5`, then `x = x + 2`, then `x = x * 2`. What is the value of `x` at the end?",[],{"value":69,"tolerance":4,"unit":38},14,"Work through one line at a time, using the value that x has just before that line runs.","After the first line x is 5. The second line reads 5, adds 2 and stores 7. The third reads 7, doubles it and stores 14. Each assignment uses the current value on its right-hand side and replaces it on the left. This step of reading, computing and storing is exactly what an accumulator does on every pass of a loop.",{"kind":73,"title":74,"blocks":75},"explanation","One variable that remembers",[76,79,87,90,93,98,103],{"id":77,"depth":37,"emphasis":38,"type":39,"markdown":78},"explain-pattern","A loop looks at one item at a time and forgets it when it moves on. To answer a question about the *whole* list, something has to carry information from one pass to the next. That something is an ordinary variable, called an **accumulator**. Every accumulator loop has three parts:\n\n1. **Before the loop: initialise.** Give the accumulator its starting value: what the answer should be before any item has been looked at. For a total that is `0`.\n2. **Inside the loop: update.** Combine the accumulator with the current item and store the result back.\n3. **After the loop: use the result.** Only now does the accumulator hold the answer for the whole list.\n\nHere is a total over `[4, 7, 1]`, traced by hand. `total` starts at 0.\n\n- Pass 1: the item is 4, so `total = total + 4` stores 4.\n- Pass 2: the item is 7, so `total` becomes 4 + 7 = 11.\n- Pass 3: the item is 1, so `total` becomes 11 + 1 = 12.\n\nThe loop ends and `total` is 12. Run the program below to watch the same thing happen.",{"id":80,"depth":37,"emphasis":38,"type":21,"language":81,"title":82,"instructions":83,"setup":38,"starter_code":84,"solution":38,"tests":85,"time_limit_ms":86},"explain-trace","python","Run it: watch a total build up","This program is complete. Run it and match each printed line to one pass of the loop. Then change the numbers in `prices`, predict the final total, and run it again to check.","prices = [4, 7, 1]\n\ntotal = 0                      # 1. before the loop: start at zero\nfor price in prices:\n    total = total + price      # 2. inside the loop: update\n    print(\"added\", price, \"-> total is now\", total)\n\nprint(\"Final total:\", total)   # 3. after the loop: use the result\n",[],5000,{"id":88,"depth":37,"emphasis":38,"type":39,"markdown":89},"explain-count","**Counting is the same pattern with a different update.** To count, add 1 instead of adding the item. To count only *some* of the items, put the update under an `if`:\n\n- initialise: `count = 0`\n- update, inside the loop: `if price > 5:` and, indented under it, `count = count + 1`\n- result for `[4, 7, 1]`: only 7 passes the test, so `count` ends at 1\n\nPython lets you shorten these updates: `total += price` means `total = total + price`, and `count += 1` means `count = count + 1`.",{"id":91,"depth":37,"emphasis":38,"type":39,"markdown":92},"explain-maximum","**Finding a maximum: remember the best so far.** Here the accumulator holds the largest item seen up to now, and the update *replaces* it whenever the current item is bigger:\n\n- initialise: `largest = numbers[0]`, the first item\n- update, inside the loop: `if number > largest:` and, indented under it, `largest = number`\n\nFor `[4, 7, 1]`: `largest` starts at 4. The first item, 4, is not bigger than 4, so nothing changes. Then 7 is bigger, so `largest` becomes 7. Then 1 is not, so it stays 7.\n\nWhy start from the first item and not from 0? Before any item has been seen there is no sensible 'largest so far', so a made-up starting value is a guess, and a guess can be wrong. If every number in the list is negative, say `[-5, -2, -9]`, a start of 0 is never replaced and the loop wrongly reports 0. Starting from the first item cannot go wrong in this way. (It does need the list to have at least one item.)",{"id":94,"depth":37,"emphasis":38,"type":52,"tone":95,"title":96,"markdown":97},"explain-key","key_idea","The accumulator pattern","**Initialise** before the loop, **update** inside it, **use** the result after it. Only the starting value and the update line change from one problem to the next:\n\n- total: start at `0`, update with `total = total + item`\n- count: start at `0`, update with `count = count + 1`, usually under an `if`\n- maximum: start with the first item, update with `largest = item` under `if item > largest:`",{"id":99,"depth":47,"emphasis":38,"type":52,"tone":100,"title":101,"markdown":102},"explain-mistakes","caution","Three mistakes to recognise","- **Initialising inside the loop.** If `total = 0` is indented under the `for`, the total is reset on every pass and ends up equal to the last item alone.\n- **Using the result too early.** A `return total` indented under the `for` leaves the function during the first pass, before the other items have been seen. A `print(total)` in the same place prints a running total on every pass instead of one final answer.\n- **A starting value that does not fit the data.** Starting a maximum at 0 fails for a list of negative numbers; starting a minimum at 0 fails for a list of positive ones.",{"id":104,"depth":105,"emphasis":38,"type":106,"title":107,"blocks":108},"explain-beyond","extended","expandable","Accumulators that are not totals",[109],{"id":110,"depth":105,"emphasis":38,"type":39,"markdown":111},"beyond-numbers","The pattern does not care what the accumulator holds or how it is combined with each item.\n\n- **A product.** Start at `1` and update with `product = product * item`. The starting value is always the one that leaves the first item unchanged: 0 for adding, 1 for multiplying.\n- **A new list.** Start with an empty list, `selected = []`, and update with `selected.append(item)` under an `if`. This is how a list is filtered.\n- **Text.** Start with an empty string, `initials = \"\"`, and update with `initials = initials + name[0]`.\n- **A yes-or-no answer.** Start with `found = False` and set `found = True` under an `if`. After the loop, `found` says whether any item passed the test.\n\nIn each case ask the same three questions: what should the accumulator hold before any item has been seen, how does one more item change it, and where do I read the result?",{"kind":113,"title":114,"blocks":115},"illustration","One loop, three answers",[116,149,155],{"id":117,"depth":47,"emphasis":38,"type":118,"title":119,"description":120,"kind":121,"direction":122,"nodes":123,"edges":140},"illustrate-flow","diagram","The flow of an accumulator loop","A flow diagram. The accumulator is initialised once. The loop then asks whether another item is left: if so, it updates the accumulator with that item and asks again; if not, the loop ends and the result is used.","flow","down",[124,128,132,136],{"id":125,"label":126,"detail":127,"group":38},"initialise","Initialise the accumulator","Runs once, before the loop. Example: total = 0",{"id":129,"label":130,"detail":131,"group":38},"next-item","Is there another item?","The for statement takes the next item from the list, if one is left.",{"id":133,"label":134,"detail":135,"group":38},"update","Update the accumulator","Runs once for each item, inside the loop. Example: total = total + price",{"id":137,"label":138,"detail":139,"group":38},"result","Use the result","Runs once, after the loop. Example: print(total)",[141,143,145,147],{"source":125,"target":129,"label":38,"directed":142},true,{"source":129,"target":133,"label":144,"directed":142},"yes",{"source":133,"target":129,"label":146,"directed":142},"back to the top",{"source":129,"target":137,"label":148,"directed":142},"no items left",{"id":150,"depth":47,"emphasis":38,"type":21,"language":81,"title":151,"instructions":152,"setup":38,"starter_code":153,"solution":38,"tests":154,"time_limit_ms":86},"illustrate-three","Run it: a total, a count and a maximum in one loop","One pass over the data can feed several accumulators at once. Run the program, then try these changes one at a time, predicting the output before each run:\n\n1. Change the test so that it counts the days of 20 degrees or more.\n2. Add a temperature of 25 to the list.\n3. Move the line `total = 0` to just below the `for` line, indented to match the loop body, and see what the bug does to the total and the average. Then move it back.","temperatures = [12, 17, 9, 21, 17, 14]\n\ntotal = 0\nwarm_days = 0\nhighest = temperatures[0]\n\nfor t in temperatures:\n    total = total + t                # total: add the item\n    if t >= 15:\n        warm_days = warm_days + 1    # count: add 1 when the test is true\n    if t > highest:\n        highest = t                  # maximum: replace when the item is bigger\n\nprint(\"Total:\", total)\nprint(\"Warm days (15 or more):\", warm_days)\nprint(\"Highest:\", highest)\nprint(\"Average:\", total \u002F len(temperatures))\n",[],{"id":156,"depth":47,"emphasis":38,"type":39,"markdown":157},"illustrate-average","Unchanged, the program prints a total of 90, 3 warm days, a highest temperature of 21 and an average of 15.0. Notice that the average is not a fourth pattern: it is a total divided by a count. Many summary figures are built in this way from the three basic accumulators.",{"kind":159,"title":160,"blocks":161},"exercise","Write the three loops",[162,165,192,214],{"id":163,"depth":37,"emphasis":38,"type":39,"markdown":164},"exercise-intro","Time to write the pattern yourself. The program below analyses a week of step counts with three functions. Each function receives a list and must return one value. The `def` lines, the descriptions and the final `print` lines are already written. Your job is the loop inside each function.\n\nWork on one function at a time and run the tests after each. For this exercise, write the loops by hand: do not use `sum()`, `max()`, `min()` or sorting.",{"id":166,"depth":37,"emphasis":38,"type":21,"language":81,"title":167,"instructions":168,"setup":38,"starter_code":169,"solution":170,"tests":171,"time_limit_ms":86},"exercise-lab","Three accumulators: total, count and largest","Complete the three functions.\n\n1. `total(numbers)` returns the sum of the numbers. The accumulator `result` is already initialised and returned; add the loop that updates it.\n2. `count_at_least(numbers, limit)` returns how many of the numbers are greater than or equal to `limit`. Write all three parts yourself.\n3. `largest(numbers)` returns the biggest number. Start from the first item and let bigger items replace it.\n\nWhen everything works the program prints `Total steps: 59870`, `Days at or above 8000: 4` and `Best day: 15020`, and all the tests pass. The tests also try other lists, including an empty one and one in which every number is negative.","def total(numbers):\n    \"\"\"Return the sum of the numbers. An empty list gives 0.\"\"\"\n    result = 0\n    # 1. Add each number to result.\n\n    return result\n\n\ndef count_at_least(numbers, limit):\n    \"\"\"Return how many numbers are greater than or equal to limit.\"\"\"\n    # 2. Initialise a counter, update it in a loop, then return it.\n    return 0\n\n\ndef largest(numbers):\n    \"\"\"Return the largest number. The list has at least one item.\"\"\"\n    # 3. Start from the first item and let bigger items replace it.\n    return numbers[0]\n\n\nsteps = [8200, 4100, 12050, 9900, 3000, 15020, 7600]\nprint(\"Total steps:\", total(steps))\nprint(\"Days at or above 8000:\", count_at_least(steps, 8000))\nprint(\"Best day:\", largest(steps))\n","def total(numbers):\n    \"\"\"Return the sum of the numbers. An empty list gives 0.\"\"\"\n    result = 0\n    for number in numbers:\n        result = result + number\n    return result\n\n\ndef count_at_least(numbers, limit):\n    \"\"\"Return how many numbers are greater than or equal to limit.\"\"\"\n    count = 0\n    for number in numbers:\n        if number >= limit:\n            count = count + 1\n    return count\n\n\ndef largest(numbers):\n    \"\"\"Return the largest number. The list has at least one item.\"\"\"\n    biggest = numbers[0]\n    for number in numbers:\n        if number > biggest:\n            biggest = number\n    return biggest\n\n\nsteps = [8200, 4100, 12050, 9900, 3000, 15020, 7600]\nprint(\"Total steps:\", total(steps))\nprint(\"Days at or above 8000:\", count_at_least(steps, 8000))\nprint(\"Best day:\", largest(steps))\n",[172,176,180,184,188],{"id":173,"description":174,"code":175},"total-adds-every-number","total adds up every number, and gives 0 for an empty list","assert total([1, 2, 3]) == 6, \"total([1, 2, 3]) should be 6\"\nassert total([10]) == 10, \"total([10]) should be 10\"\nassert total([-5, 5, 2.5]) == 2.5, \"total should cope with negative numbers and decimals\"\nassert total([]) == 0, \"total([]) should be 0: with no items, the starting value is the answer\"\n",{"id":177,"description":178,"code":179},"count-uses-the-condition","count_at_least counts only the numbers that reach the limit","assert count_at_least([3, 8, 5, 8, 1], 5) == 3, \"three of [3, 8, 5, 8, 1] are 5 or more\"\nassert count_at_least([2, 2, 2], 2) == 3, \"a number equal to the limit should be counted\"\nassert count_at_least([3, 8, 5], 9) == 0, \"none of [3, 8, 5] reaches 9\"\nassert count_at_least([], 1) == 0, \"an empty list has nothing to count\"\n",{"id":181,"description":182,"code":183},"largest-in-any-position","largest finds the biggest number wherever it sits in the list","assert largest([9, 4, 2]) == 9, \"the largest item may come first\"\nassert largest([4, 9, 2]) == 9, \"the largest item may be in the middle\"\nassert largest([2, 4, 9]) == 9, \"the largest item may come last\"\nassert largest([7]) == 7, \"in a one-item list, that item is the largest\"\ndata = [4, 9, 2]\nlargest(data)\nassert data == [4, 9, 2], \"largest should not change the list it is given\"\n",{"id":185,"description":186,"code":187},"largest-with-negative-numbers","largest still works when every number is negative","assert largest([-5, -2, -9]) == -2, \"largest([-5, -2, -9]) should be -2: do not start from 0\"\n",{"id":189,"description":190,"code":191},"loops-written-by-hand","the three functions use their own loops, not sum, max, min or sorting","for function in (total, count_at_least, largest):\n    shortcuts = {\"sum\", \"max\", \"min\", \"sorted\", \"sort\"} & set(function.__code__.co_names)\n    assert not shortcuts, (\n        function.__name__ + \" uses \" + sorted(shortcuts)[0]\n        + \"; write the loop by hand in this exercise\"\n    )\n",{"id":193,"depth":47,"emphasis":38,"type":22,"kind":194,"prompt":195,"options":196,"numeric":38,"hint":38,"explanation":213},"exercise-debug","single","A function is meant to return the total of a list, but for every list with items in it, it returns the first item alone. Which bug causes exactly that?",[197,201,205,209],{"id":198,"text":199,"correct":142,"feedback":200},"a","The return line is indented inside the for loop, after the update.","Correct. During the first pass the update adds the first item to 0, and then the return ends the function at once. The other items are never visited.",{"id":202,"text":203,"correct":6,"feedback":204},"b","The accumulator is set to 0 inside the for loop, before the update.","That bug resets the total on every pass, so the function returns the last item alone, not the first.",{"id":206,"text":207,"correct":6,"feedback":208},"c","The update adds 1 instead of adding the item.","That turns the total into a count: the function would return the number of items in the list.",{"id":210,"text":211,"correct":6,"feedback":212},"d","The function has no return line at all.","A Python function that finishes without reaching a return gives back None, not the first item.","A return ends the function immediately, wherever it is. Indented under the for, it runs at the end of the first pass, so only the first item has been added. The return belongs after the loop, at the same indentation as the for line.",{"id":215,"depth":105,"emphasis":51,"type":21,"language":81,"title":216,"instructions":217,"setup":38,"starter_code":218,"solution":219,"tests":220,"time_limit_ms":86},"exercise-extra","Optional practice: an average and a longest word","Two variations on the pattern.\n\n1. `mean(numbers)` returns the average. Keep **two** accumulators in one loop, a running total and a count, and divide after the loop. Do not use `sum()` or `len()` here.\n2. `longest_word(words)` returns the longest word in the list. The accumulator should hold the best *word* seen so far, not only its length. If several words share the greatest length, return the first of them.\n\nBoth lists always have at least one item. When both functions work the program prints `Mean reading: 20.5` and `Longest word: accumulator`.","def mean(numbers):\n    \"\"\"Return the average of the numbers. The list has at least one item.\"\"\"\n    # Keep two accumulators in one loop: a running total and a count.\n    return 0\n\n\ndef longest_word(words):\n    \"\"\"Return the longest word. If several tie, return the first of them.\"\"\"\n    # Remember the best word seen so far, starting with the first word.\n    return \"\"\n\n\nreadings = [18.5, 21.0, 19.5, 23.0]\nprint(\"Mean reading:\", mean(readings))\nprint(\"Longest word:\", longest_word([\"loop\", \"accumulator\", \"total\", \"initialise\"]))\n","def mean(numbers):\n    \"\"\"Return the average of the numbers. The list has at least one item.\"\"\"\n    total = 0\n    count = 0\n    for number in numbers:\n        total = total + number\n        count = count + 1\n    return total \u002F count\n\n\ndef longest_word(words):\n    \"\"\"Return the longest word. If several tie, return the first of them.\"\"\"\n    best = words[0]\n    for word in words:\n        if len(word) > len(best):\n            best = word\n    return best\n\n\nreadings = [18.5, 21.0, 19.5, 23.0]\nprint(\"Mean reading:\", mean(readings))\nprint(\"Longest word:\", longest_word([\"loop\", \"accumulator\", \"total\", \"initialise\"]))\n",[221,225,229,233,237],{"id":222,"description":223,"code":224},"mean-divides-total-by-count","mean returns the total divided by the number of items","assert mean([2, 4, 6]) == 4, \"mean([2, 4, 6]) should be 4\"\nassert mean([5]) == 5, \"the mean of a one-item list is that item\"\nassert abs(mean([1, 2]) - 1.5) \u003C 1e-9, \"mean([1, 2]) should be 1.5\"\nassert abs(mean([-3, 3, 9]) - 3) \u003C 1e-9, \"mean([-3, 3, 9]) should be 3\"\n",{"id":226,"description":227,"code":228},"mean-keeps-two-accumulators","mean keeps its own total and count instead of calling sum or len","shortcuts = {\"sum\", \"len\"} & set(mean.__code__.co_names)\nassert not shortcuts, (\n    \"mean uses \" + sorted(shortcuts)[0]\n    + \"; keep a running total and a count inside the loop instead\"\n)\n",{"id":230,"description":231,"code":232},"longest-in-any-position","longest_word finds the longest word wherever it sits in the list","assert longest_word([\"abcd\", \"a\", \"ab\"]) == \"abcd\", \"the longest word may come first\"\nassert longest_word([\"a\", \"abc\", \"ab\"]) == \"abc\", \"the longest word may be in the middle\"\nassert longest_word([\"a\", \"ab\", \"abcde\"]) == \"abcde\", \"the longest word may come last\"\nassert longest_word([\"solo\"]) == \"solo\", \"in a one-word list, that word is the longest\"\n",{"id":234,"description":235,"code":236},"longest-first-of-a-tie","when several words tie for longest, the first of them is returned","assert longest_word([\"tea\", \"cup\", \"mug\"]) == \"tea\", \"all three have 3 letters, so the first, 'tea', is the answer\"\nassert longest_word([\"to\", \"kettle\", \"be\", \"teapot\"]) == \"kettle\", \"'kettle' and 'teapot' tie, and 'kettle' comes first\"\n",{"id":238,"description":239,"code":240},"longest-written-by-hand","longest_word uses its own loop, not max or sorting","shortcuts = {\"max\", \"sorted\", \"sort\"} & set(longest_word.__code__.co_names)\nassert not shortcuts, (\n    \"longest_word uses \" + sorted(shortcuts)[0] + \"; write the loop by hand in this exercise\"\n)\n",{"kind":242,"title":243,"blocks":244},"check","Check your understanding",[245,253,270],{"id":246,"depth":37,"emphasis":38,"type":22,"kind":65,"prompt":247,"options":248,"numeric":249,"hint":251,"explanation":252},"check-start-value","A program runs these three lines in order. What number does it print?\n\n1. `total = 10`\n2. `for n in [1, 2, 3]: total = total + n`\n3. `print(total)`\n\n(The body of the loop is written on the same line as the `for` to save space. It still runs once for each item.)",[],{"value":250,"tolerance":4,"unit":38},16,"Trace it pass by pass. What does total hold before the first pass?","The accumulator starts at 10, not 0, and each pass adds one item: 10 + 1 = 11, then 11 + 2 = 13, then 13 + 3 = 16. An answer of 6 ignores the starting value; an answer of 13 adds only the last item to it. The loop never resets total, so whatever it held before the loop is part of the result.",{"id":254,"depth":37,"emphasis":38,"type":22,"kind":194,"prompt":255,"options":256,"numeric":38,"hint":38,"explanation":269},"check-reset-bug","A program is meant to print the total of `[5, 10, 20]`, which is 35. Instead it prints a single line: `20`. Which mistake produces exactly that output?",[257,260,263,266],{"id":198,"text":258,"correct":6,"feedback":259},"The print line is indented inside the loop, below the update.","Then the program would print three lines, one per pass, showing the running totals 5, 15 and 35. The question says that it prints a single line.",{"id":202,"text":261,"correct":6,"feedback":262},"The update line reads total = total + 1 instead of adding the item.","That counts the items instead of adding them up, so the program would print 3.",{"id":206,"text":264,"correct":6,"feedback":265},"The line total = 0 is missing from the program altogether.","Then the first pass would try to read total before it had a value, and Python would stop with a NameError instead of printing a number.",{"id":210,"text":267,"correct":142,"feedback":268},"The line total = 0 is indented inside the loop, above the update.","Correct. Every pass resets total to 0 and then adds the current item, so after the last pass total holds only the last item, 20.","Where a line sits in relation to the loop decides how often it runs. Initialisation belongs before the loop, so that it runs once. Inside the loop it runs on every pass and wipes out what the accumulator has gathered, leaving only the contribution of the final item.",{"id":271,"depth":37,"emphasis":38,"type":22,"kind":194,"prompt":272,"options":273,"numeric":38,"hint":38,"explanation":286},"check-max-start","A function finds the largest number in a list. It starts with `largest = 0` and, for each number `n` in the list, replaces `largest` with `n` when `n > largest`. For which list does it return the wrong answer?",[274,277,280,283],{"id":198,"text":275,"correct":6,"feedback":276},"[3, 9, 2]","Here it works: 3 replaces 0, then 9 replaces 3, and 2 changes nothing, so it returns 9.",{"id":202,"text":278,"correct":142,"feedback":279},"[-5, -2, -9]","Correct. None of these numbers is greater than 0, so largest is never replaced and the function returns 0, a number that is not even in the list. The right answer is −2.",{"id":206,"text":281,"correct":6,"feedback":282},"[0, 0, 0]","Here it returns 0, which is correct, though only by luck: no item ever replaces the starting value.",{"id":210,"text":284,"correct":6,"feedback":285},"[7]","Here it works: 7 is greater than 0, so it replaces the starting value and the function returns 7.","An accumulator's starting value must not distort the result. For a maximum, 0 is a safe start only if you know that no list will ever consist entirely of negative numbers. Starting from the first item of the list removes that assumption: the result is then always a number that really is in the list.",{"kind":288,"title":289,"blocks":290},"next","Where this leads",[291,294],{"id":292,"depth":47,"emphasis":38,"type":39,"markdown":293},"next-unlocks","The accumulator pattern is the basis for a good deal of what comes next.\n\n- **Other accumulators.** The same three parts build a product, a minimum, a new list of selected items, or a piece of text joined from parts.\n- **Loops with an index.** `for i in range(len(numbers)):` lets the update refer to positions, which you need for questions such as *where* the largest item is.\n- **Dictionaries as accumulators.** Counting how often each word appears in a text uses one counter per word, stored in a dictionary.\n- **The built-ins and beyond.** Knowing what `sum()`, `max()` and `len()` do inside makes them, and tools such as list comprehensions, easier to trust and to combine.",{"id":295,"depth":47,"emphasis":38,"type":52,"tone":296,"title":297,"markdown":298},"next-try","tip","One thing to try","Go back to the main exercise and add a fourth function, `smallest(numbers)`, by changing as little as possible in your `largest`. Which single character of the loop has to change? Then test it on a list of positive numbers, and ask yourself why a start of `0` would have failed there.",[300,303,305,307,310,313,316],{"term":301,"definition":302},"accumulator","A variable that is updated on each pass of a loop, so that it carries a result such as a total from one item to the next.",{"term":125,"definition":304},"To give a variable its first value. An accumulator is initialised once, before the loop starts.",{"term":133,"definition":306},"To compute a new value from a variable's current value and store it back, as in total = total + price.",{"term":308,"definition":309},"iteration","One pass through the body of a loop. A for loop over a list performs one iteration for each item.",{"term":311,"definition":312},"loop body","The indented lines under a for statement, which run once for each item.",{"term":314,"definition":315},"running total","The value of a total part-way through a loop: the sum of the items seen so far.",{"term":317,"definition":318},"trace","To follow a program by hand, line by line, writing down the value of each variable as it changes.",[],"24bdceda0fa5dda6c8500e67313e4ca631675f4d9e81b7a2f3978bb3d68cdb35","2026-10-20T20:13:41.445616Z",{"origin":323,"reviewed":6,"flagged":6,"note":324,"concept_known":38},"curated","Sample lesson. Python's built-in sum(), len(), max() and min() do these jobs in everyday code; the lesson writes the loops by hand so that the pattern itself is clear. It assumes you have already met lists, for loops, if statements and simple functions. The code runs in your browser.",{"check":326,"tutor":344,"challenge":351,"explanations":357,"more":441},{"turns":327},[328,331,334,336,338,340,342],{"role":329,"content":330},"examiner","Hi, and welcome to this lesson's check. It's just a short, casual conversation about how you think of the lesson's idea: nothing is graded and there's no pressure at all. First question: how would you explain to someone what an accumulator is, and why a loop needs one?",{"role":332,"content":333},"student","A for loop only looks at one item at a time and forgets it when it moves on to the next, so if you want an answer about the whole list you need a variable that carries something from one pass to the next. That's the accumulator. You set it up before the loop, like total = 0, change it once for each item inside the loop, and only read it after the loop has finished, because that's the first moment it has seen everything.",{"role":329,"content":335},"Thank you. You said you set it up before the loop. How do you decide what its starting value should be?",{"role":332,"content":337},"It should be what the answer is before any item has been looked at, so it can't spoil the result. For a total or a count that's 0. For a product it would have to be 1, because starting at 0 would make everything 0. For the largest item there isn't a sensible answer before you've seen anything, so you start with the first item instead of guessing something like 0, which goes wrong if every number in the list is negative.",{"role":329,"content":339},"Thank you. Second and last question: say you want to know how many words in a list are longer than five letters. What would your three parts be?",{"role":332,"content":341},"Before the loop, count = 0. Inside the loop, for word in words, then an if that checks whether len(word) is greater than 5, and only under that if, count = count + 1, so it goes up for the long words and stays put for the rest. After the loop, count is the answer, so the return or the print goes there, at the same indentation as the for, not inside the loop.",{"role":329,"content":343},"Thank you, that's the end of this check. The idea seems to be yours: you explained why a loop needs a variable that remembers, put its three parts before, inside and after the loop, chose starting values for good reasons, including why a maximum starts from the first item, and built a conditional count of your own. The skill's Mastery Check is where you demonstrate it.",{"turns":345},[346,348],{"role":332,"content":347},"Why does the maximum start with numbers[0] and then still loop over every item, including the first one again? Wouldn't it be cleaner to skip the first item, since it's already been used?",{"role":349,"content":350},"tutor","Good question. When the loop sees the first item again, what does the comparison `number > largest` do if both are `numbers[0]`? Does that change `largest`?\n\nYou can skip the first item too; starting at `numbers[0]` and looping over everything is just simpler, because that first comparison is harmless.",{"turns":352},[353,355],{"role":332,"content":354},"An accumulator is a variable that carries an answer from one pass of a loop to the next. You give it a starting value before the loop, update it once for every item inside the loop, and only use it after the loop has finished. For [4, 7, 1] a total goes 0, 4, 11 and then 12. Between a total, a count and a maximum, the only things that change are the starting value and the update line.",{"role":349,"content":356},"You’ve got the accumulator’s role, the three stages, and the total trace right. One small nuance: a count may update only for items that pass an `if`, rather than once for every item. How would you describe that exception in your own words?",[358,364,370,376,382,398],{"mode":359,"blocks":360},"simpler",[361],{"id":362,"depth":37,"emphasis":51,"type":39,"markdown":363},"ex-simpler-1","A loop checks a list one item at a time. An **accumulator** keeps track of an answer as the loop goes.\n\nFor a total, start at `0`, add each item inside the loop, then use the total after the loop:\n\n```python\ntotal = 0\nfor price in prices:\n    total = total + price\n```\n\nEveryday example: add each price in your shopping basket to find the total cost.\n\nThe pattern also works for other answers: to count items, add `1` for each item you want to count. To find the largest item, start with the first item and replace it when you find a larger one.",{"mode":365,"blocks":366},"worked_example",[367],{"id":368,"depth":37,"emphasis":51,"type":39,"markdown":369},"ex-worked-example-1","To total the prices `[4, 7, 1]`, keep the running answer in `total`:\n\n```python\ntotal = 0                 # Start at 0: before seeing any prices, their total is 0.\nfor price in [4, 7, 1]:\n    total = total + price # Add this price to what has been added so far.\nprint(total)               # Use the result after every price has been visited.\n```\n\nThe loop updates `total` once per pass:\n\n- Before the loop: `total` is `0`.\n- Pass 1: `price` is `4`; add it to `0`, so `total` becomes `4`.\n- Pass 2: `price` is `7`; add it to `4`, so `total` becomes `11`.\n- Pass 3: `price` is `1`; add it to `11`, so `total` becomes `12`.\n\nAfter the loop, `print(total)` prints `12`, the total for the whole list. The starting value is set before the loop so it is not reset on each pass; the result is used after the loop so all items have been included.",{"mode":371,"blocks":372},"analogy",[373],{"id":374,"depth":37,"emphasis":51,"type":39,"markdown":375},"ex-analogy-1","Think of `total` like a scorekeeper’s running tally: before the first item, the tally is 0; after each item, the scorekeeper adds that item’s value and writes down the new tally. In a loop, that is `total = 0` before the `for`, then `total = total + item` inside it. After the loop, `total` holds the total for the list.\n\n**Where the analogy stops:** a program does not understand prices or keep a human tally; it updates a variable exactly as instructed. And the same pattern does not always mean “add the item”: counting adds 1, while finding a maximum replaces the stored value when a larger item appears.",{"mode":377,"blocks":378},"socratic",[379],{"id":380,"depth":37,"emphasis":38,"type":39,"markdown":381},"ex-socratic-1","1. If a loop sees one item at a time, what would let it carry information from one pass to the next?\n2. Before a loop adds the items in `[4, 7, 1]`, what should the total be, and how would you update it for each item?\n3. For a count of items greater than 5, what should change in the accumulator, and when should that change happen?\n4. To find the largest item, what should the accumulator remember, and under what condition should it be replaced?\n5. Where should you initialise the accumulator and use its final value—and what could go wrong if either step is placed inside the loop?",{"mode":383,"blocks":384},"deeper_math",[385,389,395],{"id":386,"depth":37,"emphasis":387,"type":39,"markdown":388},"ex-deeper-math-1","theoretical","An accumulator is a state variable whose value is updated as a `for` loop processes items. The key correctness question is: **what does the accumulator represent after each pass?**\n\n```python\ntotal = 0\nfor item in items:\n    total = total + item\n# use total here\n```\n\nFor a count, update by one when the item meets the condition:\n\n```python\ncount = 0\nfor price in prices:\n    if price > 5:\n        count = count + 1\n# use count here\n```\n\nFor a maximum, the list must be nonempty:\n\n```python\nlargest = numbers[0]\nfor number in numbers:\n    if number > largest:\n        largest = number\n# use largest here\n```\n\nThe maximum loop compares each item with the best value remembered so far. It is safe to examine the first item again: it is equal to `largest`, so the strict `>` test leaves the value unchanged.",{"id":390,"depth":105,"emphasis":387,"type":391,"latex":392,"spoken":393,"caption":394},"ex-deeper-math-2","formula","\\begin{aligned}\\text{total after }k\\text{ passes} &= \\sum_{i=0}^{k-1} x_i,\\\\\\text{count after }k\\text{ passes} &= \\sum_{i=0}^{k-1} [P(x_i)],\\\\\\text{largest} &= \\max\\bigl(\\{x_0\\}\\cup\\{x_i: i\\text{ has been processed}\\}\\bigr).\\end{aligned}","After k passes, total is the sum of the first k items; count is the number among them satisfying the condition. For maximum, largest is the greatest of the initial item and every item processed so far.","Here [P(x)] is 1 when P(x) is true and 0 otherwise; assume the list for the maximum is nonempty.",{"id":396,"depth":47,"emphasis":387,"type":39,"markdown":397},"ex-deeper-math-3","These statements are loop invariants: they describe what remains true as the loop advances. For total and count, they hold initially at zero (the sum or count over no items), and each update makes them true for one more item. When all items have been processed, set $k$ to the list length, so the accumulator gives the requested whole-list result.\n\nFor maximum, the initial value is an actual list item. Each pass preserves the greatest value seen so far: if the current item is greater, replace `largest`; otherwise, keep it. After the final pass, every list item has been considered, so `largest` is the maximum. Starting at zero would not maintain this property for lists whose values are all negative.\n\nInitialise before the loop, update inside it, and use the result after it. Resetting the accumulator inside the loop discards earlier passes; using the result inside the loop gives only a partial result (or exits before the remaining items are processed).",{"mode":399,"blocks":400},"visual",[401,404,437],{"id":402,"depth":37,"emphasis":51,"type":39,"markdown":403},"ex-visual-1","Picture the list as a row of items passing through a workbench one at a time. Beside it is a note called the **accumulator**. Each pass reads the current item and changes the note; the note carries information forward for the next pass.\n\nFor a total, start the note at `0` and add each item:\n\n```python\ntotal = 0\nfor item in [4, 7, 1]:\n    total = total + item\nprint(total)\n```\n\nThe note changes `0 → 4 → 11 → 12`. After the loop, `total` is `12`.\n\nThe same pattern answers other questions, with a different starting value or update:\n\n- **Count:** start with `count = 0`; add `1` for each item to count. To count only matching items, put the update under an `if`.\n- **Maximum:** start with the first item, then replace it only when the current item is bigger: `if number > largest: largest = number`. This requires a nonempty list.\n\nInitialise before the loop, update inside it, and use the final answer after it.",{"id":405,"depth":37,"emphasis":51,"type":118,"title":406,"description":407,"kind":121,"direction":408,"nodes":409,"edges":428},"ex-visual-2","How an accumulator loop carries information","The accumulator is set before the loop, updated once per item, and used after all items have been processed.","right",[410,414,417,420,424],{"id":411,"label":412,"detail":413,"group":38},"initialize","Initialise","Set a starting value before the loop; for a total, use 0.",{"id":129,"label":415,"detail":416,"group":38},"Get next item","The loop takes one item from the list.",{"id":133,"label":418,"detail":419,"group":38},"Update accumulator","Combine the saved value with this item, or replace it when the rule calls for that.",{"id":421,"label":422,"detail":423,"group":38},"finished","No items left","The loop ends; the accumulator represents the whole list.",{"id":425,"label":426,"detail":427,"group":38},"use-result","Use result","Read, print, or return the final value after the loop.",[429,430,432,434,436],{"source":411,"target":129,"label":38,"directed":142},{"source":129,"target":133,"label":431,"directed":142},"item available",{"source":133,"target":129,"label":433,"directed":142},"next pass",{"source":129,"target":421,"label":435,"directed":142},"list exhausted",{"source":421,"target":425,"label":38,"directed":142},{"id":438,"depth":47,"emphasis":51,"type":52,"tone":100,"title":439,"markdown":440},"ex-visual-3","Put each step in the right place","If you initialise inside the loop, the saved value resets on every pass. If you use or return the result inside the loop, you act before all items have been seen. Put initialisation before `for`, the update in its indented body, and use the result after the loop.",{"blocks":442},[443,446],{"id":444,"depth":47,"emphasis":51,"type":39,"markdown":445},"ex-more-1","A maximum is undefined for an empty list: there is no item that could be the largest. If a function should accept empty lists, make that case explicit rather than choosing a numeric starting value:\n\n```python\ndef largest_or_none(numbers):\n    if not numbers:\n        return None\n\n    largest = numbers[0]\n    for number in numbers[1:]:\n        if number > largest:\n            largest = number\n    return largest\n```\n\nHere `None` signals “there was no maximum.” A caller can check for it before treating the result as a number. The loop begins with `numbers[1:]` because the first item already supplies the initial candidate; the empty-list check must come first so that `numbers[0]` is never accessed when there is no item.",{"id":447,"depth":105,"emphasis":387,"type":52,"tone":95,"title":448,"markdown":449},"ex-more-2","A loop invariant is a way to check the reasoning","A **loop invariant** is a statement that remains true at each step of a loop. For the maximum-finding code above, after it has considered the first *k* items, `largest` is the greatest of those *k* items. It is true initially for the first item; each comparison preserves it; when the loop ends, all items have been considered, so it gives the answer. This is the core shape of a correctness argument, not just a way to trace values. Assertion-based program verification was developed by Robert W. Floyd, and C. A. R. Hoare later formalized program reasoning in Hoare logic.",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":451},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"m12 19l-7-7l7-7m7 7H5\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":453},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M15 14c.2-1 .7-1.7 1.5-2.5c1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5c.7.7 1.3 1.5 1.5 2.5m0 4h6m-5 4h4\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":455},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M5 12h14m-7-7v14\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":457},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M5 12h14m-7-7l7 7l-7 7\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":459},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"m6 9l6 6l6-6\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":461},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092a10 10 0 1 0-4.777-4.719\"\u002F>",{"left":4,"top":4,"width":5,"height":5,"rotate":4,"vFlip":6,"hFlip":6,"body":463},"\u003Cpath fill=\"none\" stroke=\"currentColor\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"m13 19l6-6m-4.5 4.5L3.586 6.586A2 2 0 0 1 3 5.172V3h2.172a2 2 0 0 1 1.414.586L17.5 14.5m-2.672-8.328l2.586-2.586A2 2 0 0 1 18.828 3H21v2.172a2 2 0 0 1-.586 1.414l-2.586 2.586M16 16l4 4m-1 1l2-2M5 14l4 4m-4 3l-2-2m4.5-2.5L4 20\"\u002F>"]