3.08 Iterations
Use Python for loops, while loops, continue, and break to process repeated data.
1. Reference Guide
Key Topics
| Term | Definition | Example |
|---|---|---|
| Iteration | Repeating a block of instructions. | Checking every alert in a list. |
| Loop body | The indented code that repeats. | print(reading) inside a loop. |
| Loop variable | A variable that changes each pass through a for loop. |
for reading in readings: |
| Condition | A true/false expression that controls a decision or loop. | temperature > 30 |
| Accumulator | A variable that gathers a total or count over time. | action_count += 1 |
| Sentinel / stop condition | A value or condition that tells a loop to stop. | alert >= critical_cutoff |
continue |
Skips the rest of the current loop pass. | Skip safe alerts. |
break |
Stops the loop immediately. | Stop at a critical alert. |
Python Iteration Tools
| Tool | Meaning | Example | Notes |
|---|---|---|---|
for |
Repeats once for each item in a sequence. | for score in scores: |
Best for lists. |
while |
Repeats while a condition is true. | while temp > 30: |
Needs an update inside the loop. |
continue |
Skips to the next loop pass. | continue |
Useful for filtering. |
break |
Exits the loop early. | break |
Useful after finding a critical case. |
| Counter | Tracks how many matches were found. | count += 1 |
Starts at 0. |
| Running total | Adds values over time. | total += value |
Starts at 0. |
College Board Pseudocode Connections
| College Board pseudocode | Python connection | Python example | When to use it |
|---|---|---|---|
REPEAT n TIMES |
for _ in range(n): |
for _ in range(5): print("check") |
Repeat a known number of times. |
REPEAT UNTIL(condition) |
while not condition: |
while not safe: safe = check_status() |
Repeat until a stopping condition becomes true. |
| List traversal with an index | for item in values: or for i in range(len(values)): |
for i in range(len(readings)): print(readings[i]) |
Inspect every item in a list. |
| Boolean expression in a loop | while temperature > 30: |
while temperature > 30: temperature -= 5 |
Keep looping while the condition is true. |
| Accumulator update | total += value |
total = 0; for score in scores: total += score |
Count or total values during repetition. |
College Board pseudocode does not use Python indentation, but the algorithmic idea is the same: identify what repeats, identify the condition, and trace how variables change each pass.
Picking a Loop
- Known list or sequence ->
for - Repeat until safe ->
while - Ignore safe values ->
continue - Stop at the first critical value ->
break - Need a count or total -> accumulator variable
Quick Check (2 minutes)
Choose the best option before moving on. This is a short check to make sure you know when a loop should keep going, skip a value, or stop.
2. LxD Cycle Process
Empathize: Students often know that loops repeat, but they still copy and paste code because they do not know how to choose the right loop shape. They also mix up break and continue, and while loops feel dangerous when the update step is missing.
Define:
- POV: Python students need to choose loops from the task’s goal, because the loop type determines whether repeated work is clear, safe, and correct.
- Learning Goal: Students will trace and write
forloops,whileloops,continue, andbreakto inspect data, skip safe values, count matches, and stop at a critical condition.
Ideate:
- HMW Question: How might we get students to ask “what should make this loop keep going or stop?” before writing code?
- HMW Question: How might we show the difference between skipping one item and stopping the whole scan?
- HMW Question: How might we make
forloops feel different fromwhileloops through the problem setup? - HMW Question: How might we help students debug a loop that runs forever or stops too early?
- HMW Question: How might we make students prove their loop worked by printing a useful final summary?
- Activity: Use an SFSRC wildfire-response data scan. Students read a reference guide, run examples, fix a broken popcorn hack, answer MCQs, then build a small SFSRC-style loop-based checker.
Prototype:
- A reference guide, runnable Python examples, a broken SFSRC dispatch popcorn hack, an MCQ knowledge check, and a scaffolded monitoring-system homework checker.
- Students revise loop conditions after seeing syntax or logic errors in CodeRunner.
- Excellence means explaining why each loop control statement is used, not only making the code run.
Test:
- Ask peers to complete the popcorn hack without extra hints.
- Observe whether peers choose
continuefor skipping andbreakfor stopping. - Compare this lesson with another that is posted.
- Use the findings to revise any instruction or rubric criterion that did not guide students clearly.
- On submission, collect evidence from runner output, MCQ results, AI grading, and student explanations.
- After teaching, grading, and analysis, come back and revise the lesson to complete the teaching cycle for continuous improvement.
3. College Board Requirements
From the College Board
AP CSP Big Idea 3 focuses on algorithms and programming. Iteration is one of the core algorithmic structures students use to express repeated work.
- Iteration: Algorithms can repeat instructions a fixed number of times or until a condition is met.
- List traversal: College Board exam language includes the skill: “Write iteration statements to traverse a list.”
REPEAT UNTIL(condition): College Board pseudocode uses this structure for condition-controlled repetition; if the ending condition never becomes true, the loop can run forever.- Boolean conditions: Loop conditions evaluate to true or false and control whether repetition continues.
- Algorithm analysis: Students should be able to trace loop behavior and explain how a repeated process changes variables.
The College Board pseudocode version of an SFSRC alert scan might look like this:
activeCount <- 0
REPEAT UNTIL(alertIndex > LENGTH(alerts))
{
IF(alerts[alertIndex] >= 3)
{
activeCount <- activeCount + 1
}
alertIndex <- alertIndex + 1
}
Python uses for loops and while loops to express these repetition patterns. This lesson uses Python syntax, but the reasoning transfers to College Board pseudocode such as REPEAT n TIMES, REPEAT UNTIL(condition), list traversal, and accumulator updates. When you trace a Python loop, you should be able to explain the same algorithm in College Board pseudocode: what repeats, what condition is checked, and which variables change.
4. Lesson Plan
Learning Objective: Use iteration to process repeated data and control when a loop skips, continues, or stops.
Success Criteria: You can choose for or while, update loop variables safely, use continue to skip a loop pass, use break to stop early, and print a clear final summary.
Tech Talk (5 minutes)
A loop repeats a block of code. Every loop needs a purpose: inspect a list, count matching values, keep working until safe, or stop when something important is found.
Pick the loop by asking two questions:
- Am I repeating over a known sequence?
- What condition should make the repetition stop?
Example shapes: for reading in readings: traverses a list, while while cooling > 30: repeats until a safety condition changes.
continue skips the rest of one loop pass. break exits the loop completely. College Board pseudocode usually describes these ideas through loop conditions and algorithm steps, so in explanations you should say whether the algorithm skips the current value, keeps repeating, or stops because the goal was reached.
5. Code Examples
A. Simple iteration. The for loop scans SFSRC zone readings, classifies each zone, and prints the result.
Loop pattern:
for item in items:
if item meets a condition:
do one thing
else:
do another thing
Terminology:
The loop variable reading changes each pass. The list readings is the sequence being traversed.
Code Runner Challenge
Simple Iteration Example - SFSRC zone scan
View IPYNB Source
# CODE_RUNNER: Simple Iteration Example - SFSRC zone scan
zone_readings = [34, 42, 31, 48]
alert_cutoff = 40
for reading in zone_readings:
if reading >= alert_cutoff:
print(str(reading) + ": SFSRC alert")
else:
print(str(reading) + ": normal patrol")
B. Complex iteration. This SFSRC dispatch example combines while, continue, and break.
Common control-flow idea:
continue # skip this one item
break # stop the whole loop
Terminology:
A while loop depends on a condition that must eventually change. continue filters low-priority values. break stops once a critical value is found.
Code Runner Challenge
Complex Iteration Example - SFSRC cooldown and alert scan
View IPYNB Source
# CODE_RUNNER: Complex Iteration Example - SFSRC cooldown and alert scan
temperature = 85
safe_temperature = 30
while temperature > safe_temperature:
temperature -= 15
print("Cooling SFSRC equipment: " + str(temperature))
zone_alerts = [1, 3, 2, 5, 8, 4]
critical_alert = 8
for alert in zone_alerts:
if alert < 3:
continue
print("Dispatch responding to alert " + str(alert))
if alert >= critical_alert:
print("Critical SFSRC alert found")
break
6. Hacks & Practice Tasks
Prepare your submission IPYNB
- Create a new notebook in your portfolio homework area:
_notebooks/homework. -
Add one raw cell at the top with the frontmatter:
layout: post codemirror: true title: Iterations HW categories: [Python] lesson_language: Python lesson_topic: Iterations HW lesson_part: interactive lesson_type: lesson permalink: /python/iterations-hw author: yourGithubID —
- Add code cells for the Popcorn Hack and the Homework Hack. Make sure every cell runs with visible output.
-
Submit the link to your published page at the bottom of this page, and paste this in the description box:
Lesson: Python 3.08 Iterations MCQ 3.08: <paste the copied result line, such as 4/4 | answers: A,B,A,B> Popcorn: completed loop variable, thresholds, counters, continue, and break (yes/no) Homework: list length =
Homework: thresholds = , Homework: final checked count = Homework: final action count = Homework: critical found = <yes/no>
Submission Safety Rules (Read First)
- One CodeRunner task per cell, with the
# CODE_RUNNER:line at the top. - Run each cell and leave the output showing.
- Use your own values, not the sample answer.
- Include your MCQ score.
- Use
##headings or smaller.
Popcorn Hack (In-Class)
Theme: SFSRC wildfire response dispatch. You are writing a scanner for a fire response team. Low alert numbers are safe and should be skipped. Higher alert numbers need a crew response. The first critical alert should stop the scan so the team can focus.
5-minute challenge: fix the monitoring loop so it inspects values, skips safe readings, counts responses, and stops at a critical alert.
- Loop through every alert value.
- Skip alerts below the safe cutoff using
continue. - Count alerts that require action.
- Add action alerts to a running total.
- Stop at the first critical alert using
break. - Print a final summary.
Fill in every blank before you run it.
Code Runner Challenge
Popcorn Hack - wildfire dispatch scanner
View IPYNB Source
# CODE_RUNNER: Popcorn Hack - wildfire dispatch scanner
# Theme: The SFSRC team scans wildfire alert levels from different zones.
# Goal: skip safe zones, count response zones, total their alert scores, and stop at the first critical zone.
alerts = [1, 4, 2, 6, 3, 9, 5]
# TODO: Pick the cutoff for safe alerts. Alerts below this number should be skipped.
safe_cutoff = ____
# TODO: Pick the cutoff for critical alerts. The loop should stop at this number or higher.
critical_cutoff = ____
# Counters and totals start at 0 because no alerts have been processed yet.
action_count = 0
safe_count = 0
total_action_score = 0
critical_found = False
# TODO: Loop through the alert list.
for alert in ____:
# TODO: If the alert is safe, count it, print a message, and skip to the next alert.
if alert < ____:
safe_count ____ 1
print("Alert " + str(alert) + ": safe, skipping")
____
# If code reaches here, the alert needs action.
# TODO: Count this action alert and add its score to the running total.
action_count ____ 1
total_action_score ____ alert
print("Alert " + str(alert) + ": action needed")
# TODO: If this alert is critical, mark it and stop the scan.
if alert >= ____:
critical_found = ____
print("Critical alert found - stopping scan")
____
# Final report: these lines should explain what happened during the scan.
print("Safe alerts skipped: " + str(safe_count))
print("Action alerts: " + str(action_count))
print("Total action score: " + str(total_action_score))
print("Critical found: " + str(critical_found))
MCQ Check
4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.
Homework Hack
Theme: Choose your own monitoring system. Your program should feel like a small real-world checker. You can monitor SFSRC wildfire alerts, server load, battery levels, quiz scores, air quality, or another numbered system.
Task: Build a loop-based checker that takes about 10 minutes.
Your program must use at least 8 values, 2 thresholds, a for loop, continue, break, and at least 3 tracked summary values.
The theme should be obvious from your variable names and printed messages. For example, server_loads, battery_levels, or air_quality_scores is better than just values.
Solution Skeleton:
Code Runner Challenge
Homework Hack - themed loop-based checker
View IPYNB Source
# CODE_RUNNER: Homework Hack - themed loop-based checker
# Theme: Choose your own monitoring system.
# Examples: wildfire alerts, server loads, battery levels, quiz scores, or air-quality readings.
# Goal: skip safe values, count action values, total their scores, and stop at the first critical value.
# TODO: Rename values if you want a stronger theme, such as server_loads or battery_levels.
# TODO: Fill in at least 8 numbers for your scenario.
values = [____, ____, ____, ____, ____, ____, ____, ____]
# TODO: Values below safe_cutoff should be skipped with continue.
safe_cutoff = ____
# TODO: Values at or above critical_cutoff should stop the loop with break.
critical_cutoff = ____
# Summary variables. Keep these, but make sure your loop updates them correctly.
checked_count = 0
action_count = 0
skipped_count = 0
total_score = 0
critical_found = False
# TODO: Traverse every value in your list until a critical value stops the scan.
for value in values:
# TODO: Count every value the loop looks at.
checked_count ____ 1
# TODO: Skip safe values. Remember to count them before continuing.
if value < ____:
skipped_count ____ 1
print(str(value) + ": safe, no action")
____
# If code reaches here, this value needs action.
# TODO: Count it and add it to the running total.
action_count ____ 1
total_score ____ value
print(str(value) + ": action needed")
# TODO: Stop early if this value is critical.
if value >= ____:
critical_found = ____
print("Critical value found. Stop checking.")
____
# Final report. These labels should make sense for your theme.
print("Final Report")
print("Checked: " + str(checked_count))
print("Skipped: " + str(skipped_count))
print("Actions: " + str(action_count))
print("Total score: " + str(total_score))
print("Critical found: " + str(critical_found))
#%% vscode.cell [id=#VSC-a6c7fff5] [language=markdown]
Grading Plan (1 Point Total)
| Part | Points | What earns the points |
|---|---|---|
| Popcorn | 0.2 | Completed loop variable, thresholds, counters, continue, and break. |
| MCQ | 0.2 | 4 correct. 0.15 for 3 correct, 0.1 if every question was answered. |
| Homework: data setup | 0.15 | At least 8 values and 2 meaningful thresholds. |
| Homework: loop control | 0.2 | Uses continue to skip safe values and break to stop at a critical value. |
| Homework: summary values | 0.15 | Tracks checked count, skipped/action counts, and a running total. |
| Homework: final report | 0.1 | Prints a labeled final report. |
| Total | 1.0 |
Quick Validation Checklist
- Popcorn and homework cells run only after blanks are fixed.
- MCQ score is in the notes.
continueskips safe values.breakstops at the critical value.- Final report prints checked, skipped, action, total, and critical-found values.
7. Lesson Revisions
Revision Made: Reordered the lesson to match the CSA 1.2 format exactly: Reference Guide, LxD Cycle Process, College Board Requirements, Lesson Plan, Code Examples, Hacks, Popcorn Hack, MCQ Check, Homework Hack, Grading Plan, Revisions, Feedback Evidence, and References.
Revision Made: Replaced complete popcorn answers with broken starter code so students must complete loop variables, thresholds, counters, continue, and break before CodeRunner will execute successfully.
Revision Made: Added vocabulary and loop-choice tables at the top so students have definitions before they begin coding.
Revision Made: Strengthened the SFSRC wildfire-response theme so the lesson has a clear purpose beyond syntax practice.
8. Feedback Evidence
Feedback Received: The earlier version gave students too much complete code, so the popcorn hacks did not require enough thinking.
Feedback Received: The lesson needed to look and flow like the CSA 1.2 lesson, including LxD, reference tables, MCQ, popcorn hack, homework hack, grading plan, revisions, feedback evidence, and references.
Response: The revised version follows that order and keeps all content focused on Python iterations.
Feedback Received: The lesson needed a stronger theme and purpose, so the examples now connect loops to SFSRC-style alert scanning and dispatch decisions.
9. References
College Board. (2023). AP Computer Science Principles course and exam description. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-course-and-exam-description.pdf
Python Software Foundation. (2026). The Python tutorial: More control flow tools. https://docs.python.org/3/tutorial/controlflow.html
Open Coding Society. (2026). CSA Unit 1.2 Variables and Data Types lesson format. /csa/unit_01/1_2
Submit Your Homework
Once your notebook is committed and pushed, submit your portfolio link using the form below.
Submit Assignment
Need to update a submission later? Open the submissions dashboard.