- Define and explain Repeating with Loops in your own words
- Use key terms such as iteration accurately
- Apply what you have learned to new examples and questions
- Avoid the common mistakes learners make with this topic
This lesson focuses on Repeating with Loops: repeat actions efficiently with for and while loops.
Repeat actions efficiently with for and while loops.
Key ideas
Loops do the boring work
A for loop repeats a known number of times, perfect for going through a list; a while loop repeats until a condition changes, perfect when you do not know how many repeats you need. Choose wrong and you either miss items or loop forever.
Programs are input, process, output
Nearly every program follows the same shape: take something in, do something with it, and show a result. A quiz program inputs answers, processes them against the correct ones, and outputs a score. Seeing this pattern helps you plan any program before you type.
Key term — iteration: Repeating a set of instructions, usually with a for or while loop. Each single pass through the loop is one iteration.
What does this program print? First line: total = 0. Next two lines: for n in range(1, 6): then total = total + n (indented). Last line: print(total).
range(1, 6) produces the numbers 1, 2, 3, 4, 5 — the stop value 6 is not included. Start: total = 0. First iteration, n = 1, so total becomes 0 + 1 = 1. Second iteration, n = 2: total becomes 1 + 2 = 3. Third iteration, n = 3: total becomes 3 + 3 = 6. Fourth iteration, n = 4: total becomes 6 + 4 = 10. Fifth iteration, n = 5: total becomes 10 + 5 = 15. The loop ends and print(total) outputs the final value.
Answer: The program prints 15 — the sum of the numbers 1 to 5.
- Forgetting that range stops one short Correction: range(1, 6) gives 1 to 5 — always check whether your stop value is included (it never is).
- Mixing up = and == Correction: = stores a value while == compares — writing if x = 5: is a syntax error in Python; conditions need the double equals, as in if x == 5:.
Practice
11 — y * 2 is 8, plus x (3) gives 11.
0, then 1, then 2, each on its own line — range(3) starts at 0 and stops before 3.
3 — the loop runs while count is 0, 1 and 2, adding 1 each time, then stops when count reaches 3.
Hello, Ada.
Quick check
Which of these best defines "iteration"?
Write a function double(n) that returns twice its input, then state what double(7) returns.
Fix the bug: if age = 16: print('old enough for a moped')
- Repeating with Loops: repeat actions efficiently with for and while loops.
- Loops do the boring work: A for loop repeats a known number of times, perfect for going through a list; a while loop repeats until a condition changes, perfect when you do not know how many repeats you need.
- function: A named block of code that performs one task and can be called repeatedly, often with different inputs called parameters.
- Watch out for: forgetting that range stops one short