Iteration
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Repeat with iteration
- Iteration means doing the same steps again and again.
- Loops save you from writing the same line many times.
- AP CSP cares about loops because they let a little code do a lot of work.
Count with for and range
for i in range(n):repeats the bodyntimes.range(5)gives0, 1, 2, 3, 4(it stops before 5).- The loop body is indented, like an
if.
for i in range(5):
print(i)
Build a total (accumulation)
- An accumulator is a variable that grows inside a loop.
- Start it at
0before the loop. - Add to it each pass to build a running total.
total = 0
for n in range(1, 6):
total = total + n
print(total)
Loop until a condition with while
- A
whileloop repeats as long as its condition isTrue. - Something inside must move toward making it
False. - Use it when you do not know the count in advance.
count = 3
while count > 0:
print(count)
count = count - 1
Loop over a list (for-each)
for item in mylist:visits each item in turn.- The loop variable holds one item per pass.
- This is the clean way to process every value.
scores = [10, 20, 30]
for s in scores:
print(s)
In AP CSP pseudocode
- CB has three loop shapes that match Python loops.
REPEAT n TIMES= a fixed count;REPEAT UNTIL(cond)= loop until true.FOR EACH x IN list= a for-each loop.DISPLAY= print,←==,MOD=%.
REPEAT 5 TIMES
{
DISPLAY "hi"
}
count ← 3
REPEAT UNTIL (count = 0)
{
DISPLAY count
count ← count - 1
}
FOR EACH s IN scores
{
DISPLAY s
}
Now you try
- Use a loop in each task.
- Press Check answer to test your code.
Use a for loop with range(...) to add the whole numbers 1 through 10. Store the result in total. (It should be 55.)
Click Run to see the output here.
Use a while loop to print the numbers 5, 4, 3, 2, 1, each on its own line, then print Go. Start from n = 5.
Click Run to see the output here.
nums is [3, 6, 7, 8, 10, 11]. Loop over it with a for-each loop and count how many values are even (use % 2 == 0). Store the count in evens. (It should be 3.)
Click Run to see the output here.