{"base":{"id":"cs10-09","subject":"Programming","title":"Loops: counting and totalling","scene":"py10","steps":[{"mode":"forloop","eyebrow":"Count-controlled loops","title":"Repeat a set number of times","body":"A for loop repeats its indented lines once for each value. range(1, 6) gives 1, 2, 3, 4, 5: it stops BEFORE the end number. Change n and watch the loop run.","controls":[{"id":"n","label":"n","min":1,"max":6,"step":1,"value":5}],"actions":[{"id":"step","label":"Step"},{"id":"run","label":"Run"},{"id":"reset","label":"Reset"}]},{"mode":"total","eyebrow":"Totalling","title":"A running total","body":"To add up a list, start a total at 0, then add each item inside the loop. Watch the trace table: total grows by one mark each time round.","actions":[{"id":"step","label":"Step"},{"id":"run","label":"Run"},{"id":"reset","label":"Reset"}]},{"mode":"count","eyebrow":"Counting","title":"Count only what matches","body":"A counter also starts at 0, but only goes up by 1 when a condition is True. Count how many marks reach the pass mark, then change the pass mark.","controls":[{"id":"pass","label":"Pass mark","min":5,"max":20,"step":1,"value":15}],"actions":[{"id":"step","label":"Step"},{"id":"run","label":"Run"},{"id":"reset","label":"Reset"}]},{"mode":"savings","eyebrow":"Condition-controlled loops","title":"Repeat until something happens","body":"A while loop keeps going as long as its condition is True. Ava saves the same amount each week until she has at least $100. How many weeks? Change the weekly amount.","controls":[{"id":"pocket","label":"Saved each week ($)","min":10,"max":40,"step":5,"value":30}],"actions":[{"id":"step","label":"Step"},{"id":"run","label":"Run"},{"id":"reset","label":"Reset"}]},{"mode":"avgmax","eyebrow":"Putting it together","title":"Average and highest","body":"One loop can do several jobs: keep a total for the average and remember the highest value so far. Notice that highest starts at the first mark, not at 0.","actions":[{"id":"step","label":"Step"},{"id":"run","label":"Run"},{"id":"reset","label":"Reset"}]},{"mode":"quiz","look":"forloop","eyebrow":"Check yourself","title":"Count the repeats","body":"for i in range(2, 8):\n    print(i)","question":"How many times is print(i) run?","options":["8","7","6"],"answer":2,"right":"Correct. range(2, 8) gives 2, 3, 4, 5, 6, 7: six values.","wrong":"Not quite. The range starts at 2 and stops BEFORE 8."}],"more":[{"type":"cards","id":"worked","eyebrow":"Worked examples","title":"Loops to read","intro":"Predict each output before reading the comment.","items":[{"tag":"Python","title":"Times table","body":"n = 7\nfor i in range(1, 11):\n    print(i, \"x\", n, \"=\", i * n)\n# 1 x 7 = 7 … 10 x 7 = 70","code":true},{"tag":"Python","title":"Total of numbers typed in","body":"total = 0\nfor i in range(5):\n    num = int(input(\"Number? \"))\n    total = total + num\nprint(\"Total:\", total)\nprint(\"Average:\", total / 5)","code":true},{"tag":"Pseudocode","title":"FOR … NEXT and WHILE","body":"Count ← 0\nFOR i ← 1 TO 10\n  INPUT Temp\n  IF Temp > 30 THEN Count ← Count + 1\nNEXT i\nOUTPUT Count\n\nWHILE Answer <> \"yes\" DO\n  INPUT Answer\nENDWHILE","code":true},{"tag":"Pseudocode","title":"REPEAT … UNTIL (runs at least once)","body":"REPEAT\n  INPUT Mark\nUNTIL Mark >= 0 AND Mark <= 100\n\nWHILE checks first; REPEAT checks after,\nso REPEAT always runs at least once.","code":true}]},{"type":"cards","id":"mistakes","eyebrow":"Common mistakes","title":"Watch out for these","items":[{"tag":"Mistake","title":"Setting total = 0 inside the loop","body":"Then it resets every time round and you only get the last value. Initialise BEFORE the loop."},{"tag":"Mistake","title":"Off-by-one with range","body":"range(1, 10) stops at 9. To include 10, use range(1, 11)."},{"tag":"Mistake","title":"An infinite while loop","body":"If nothing inside the loop changes the condition, it never ends. Make sure the loop moves towards stopping."},{"tag":"Mistake","title":"Starting highest at 0","body":"If all values are negative, highest wrongly stays 0. Start with the first value in the list."}]},{"type":"cards","id":"method","eyebrow":"Set out your answer","title":"Choosing the right loop","items":[{"tag":"FOR","title":"You know how many times","body":"Ten students, 12 months, every item in a list: use a count-controlled FOR loop."},{"tag":"WHILE","title":"Repeat while something is true","body":"Keep going until the user types 'quit' or a target is reached. The test is at the start, so it may run zero times."},{"tag":"REPEAT","title":"Run at least once","body":"Asking for input that must be checked: ask first, then test. REPEAT … UNTIL tests at the end."}]},{"type":"calc","id":"calc","eyebrow":"Calculator","title":"Savings plan","intro":"If you save the same amount every week, how much after a year?","input":{"label":"Saved each week","min":1,"max":50,"step":1,"value":10,"unit":"$"},"rows":[{"label":"After 10 weeks","mul":10,"unit":"$","decimals":0,"color":"#2f6fdb"},{"label":"After 52 weeks","mul":52,"unit":"$","decimals":0,"color":"#1f9d55"}],"bars":true,"note":"A loop does exactly this: add the weekly amount, once per week."},{"type":"cards","id":"deeper","eyebrow":"Go deeper","title":"More than the lesson","items":[{"tag":"How it works","title":"Why computers love loops","body":"A modern processor can run billions of simple instructions per second. A loop lets five lines of code process a million records, which is why computers beat humans at repetitive jobs."},{"tag":"Real world","title":"Game loops","body":"Every video game runs a loop about 60 times a second: read the controls, update the positions, check for collisions, draw the screen, repeat. Stop the loop and the game freezes."},{"tag":"History","title":"The first loop","body":"Ada Lovelace's 1843 program for calculating Bernoulli numbers included a section to be repeated with new values: one of the earliest descriptions of a loop in a computer program."},{"tag":"Coming next","title":"Where this leads","body":"Next you'll trace loops with trace tables, then use them with arrays to search and sort lists of data."}]},{"type":"cards","id":"challenge","eyebrow":"Challenge yourself","title":"Stretch your brain","intro":"Try each one before opening the card.","items":[{"tag":"Challenge","title":"Write a loop that prints the first 10 square numbers, then their total","body":"total = 0\nfor i in range(1, 11):\n    sq = i * i\n    print(sq)\n    total = total + sq\nprint(\"Total:\", total)   # 385","code":true},{"tag":"Challenge","title":"A bacteria population doubles every hour from 1. Which loop finds when it first passes 1 million, and when?","body":"A while loop, because we don't know how many repeats:\n\npop = 1\nhours = 0\nwhile pop <= 1000000:\n    pop = pop * 2\n    hours = hours + 1\nprint(hours)   # 20 (2²⁰ = 1 048 576)","code":true}]},{"type":"activities","id":"try","eyebrow":"Try it at home","title":"Loop it","items":[{"title":"Class marks analyser","time":"25 minutes","need":["Python or an online editor"],"steps":["Store 8 marks in a list.","Use one loop to find the total, the highest and the lowest.","Print the average to 1 decimal place.","Count how many are above the average with a second loop."],"why":"Totalling, counting and finding max/min are the most common loop patterns in real programs.","safety":"No safety risks."},{"title":"Guess the number game","time":"20 minutes","need":["Python or an online editor"],"steps":["import random, then secret = random.randint(1, 50).","Use a while loop to keep asking for a guess until it's right.","After each guess print 'Higher' or 'Lower'.","Count the guesses and print the total at the end."],"why":"A while loop is perfect when you don't know how many tries it will take.","safety":"No safety risks."}]},{"type":"quiz","id":"quiz","eyebrow":"Quiz","title":"Eight more questions","questions":[{"question":"What does range(5) produce?","options":["0, 1, 2, 3, 4","1, 2, 3, 4, 5","0, 1, 2, 3, 4, 5"],"answer":0,"right":"Correct. It starts at 0 and stops before 5.","wrong":"Not quite. With one number, range starts at 0."},{"question":"Where should total = 0 go when totalling a list?","options":["Inside the loop","Before the loop","After the loop"],"answer":1,"right":"Correct. Otherwise it resets every time round.","wrong":"Not quite. It should be set only once."},{"question":"Which loop always runs at least once?","options":["FOR","WHILE","REPEAT … UNTIL"],"answer":2,"right":"Correct. It tests the condition at the end.","wrong":"Not quite. Which loop checks its condition AFTER the body?"},{"question":"count = 0; for x in [4, 9, 2, 7]: if x > 5: count += 1. What is count?","options":["2","4","16"],"answer":0,"right":"Correct. Only 9 and 7 are greater than 5.","wrong":"Not quite. Count only the values greater than 5."},{"question":"What makes a while loop infinite?","options":["Using range()","The condition never becomes False","Having more than 3 lines inside"],"answer":1,"right":"Correct. Something inside must change the condition.","wrong":"Not quite. Think about how a while loop stops."},{"question":"total = 0; for i in range(1, 4): total = total + i. What is total?","options":["10","4","6"],"answer":2,"right":"Correct. 1 + 2 + 3 = 6.","wrong":"Not quite. range(1, 4) gives 1, 2 and 3."},{"question":"Which loop is best for 'keep asking for a password until it is correct'?","options":["A condition-controlled loop","A count-controlled loop","No loop"],"answer":0,"right":"Correct. You don't know how many attempts it will take.","wrong":"Not quite. Do you know in advance how many times it will repeat?"},{"question":"What is iteration?","options":["Making a choice","Repeating steps","Storing data"],"answer":1,"right":"Correct. Loops are iteration.","wrong":"Not quite. Iteration is one of the three building blocks."}]},{"type":"checklist","id":"check","eyebrow":"Self-check","title":"I can…","items":["explain count-controlled and condition-controlled loops","write a for loop with range() and predict how many times it runs","write a while loop that is sure to stop","keep a running total in a loop","count items that meet a condition","find the highest or lowest value in a list","calculate an average from a total and a count","write loops in pseudocode with FOR, WHILE and REPEAT"]},{"type":"keywords","id":"words","eyebrow":"Key words","title":"Words to know","items":[{"word":"iteration","meaning":"Repeating a set of instructions."},{"word":"loop","meaning":"Code that repeats."},{"word":"count-controlled loop","meaning":"Repeats a set number of times (FOR)."},{"word":"condition-controlled loop","meaning":"Repeats until a condition changes (WHILE, REPEAT)."},{"word":"range()","meaning":"Python function giving a sequence of numbers; stops before the end value."},{"word":"running total","meaning":"A total that grows as each value is added."},{"word":"counter","meaning":"A variable that goes up by 1 each time something happens."},{"word":"initialise","meaning":"Give a variable its starting value."},{"word":"infinite loop","meaning":"A loop that never stops."},{"word":"pre-condition / post-condition","meaning":"Tested before (WHILE) or after (REPEAT) the loop body."}]},{"type":"sources","id":"sources","title":"Sources","items":["Python documentation: for statements; range()","BBC Bitesize, GCSE Computer Science: Iteration","Isaac Computer Science: Loops and standard algorithms","Computer History Museum: Ada Lovelace's Note G"]}]},"overlay":null}