Loops
This is the Layer 0 gate. Repeating an action for every item in a collection, or until a condition changes, is one of the most common things any program does.
The same action, repeated for every item โ or until a condition changes.
1. Learning Objective
By the end of this session you will be able to:
- Write a for loop over a list of values and explain what the loop variable holds on each pass
- Use range() to repeat an action a specific number of times
- Write a while loop and explain the risk of an infinite loop
- Use break to exit a loop early and continue to skip to the next iteration
- Combine a loop with an if statement to process only some items
2. Pre-Coding Quiz
Answer these before reading the concept explanation or writing any code. It is fine to get these wrong โ that is the point. You need 4/5 to proceed to the lab.
Given countries = ["Kenya", "Ghana", "Peru"] and the following code, what prints?
for country in countries:
print(country)
for ... in loop runs its body once for every item in the list, binding country to each value in turn. Since the body is print(country), each name prints on its own line.What does range(5) produce when looped over?
range(5) produces 5 numbers starting at 0 and stopping BEFORE 5: 0, 1, 2, 3, 4. This "starts at 0, stops before the given number" behavior matches how list indexing works, which is why it is the default.What is the danger of writing while count < 10: without ever changing count inside the loop body?
while loop keeps running as long as its condition is True. If nothing inside the loop body ever changes the value being checked, the condition never becomes False, and the loop never ends โ you must update the checked value yourself, usually near the end of the loop body.Given a loop searching for the first country with population over 100 million, what does break do once it is found?
break exits the loop immediately and completely โ useful once you have found what you were looking for and have no reason to keep checking the remaining items.Given the following, what does continue do for a country with a small population?
for c in countries:
if c["population"] < 10:
continue
print(c["name"])
continue skips only the remainder of the current iteration's body and moves the loop on to the next item โ unlike break, the loop keeps going, it just skips printing for items matching the condition.3. The Concept โ Repeating Actions with for and while
The loop body runs once per item โ country is rebound to a new value each time through.
for, while, in, break, and continue are all keywords โ reserved words that are part of Python's own syntax, not something you define. Unlike and/or/not from the last session, none of these act as operators โ they don't combine or produce a value, they control which code runs and how many times.
for loops โ repeating for every item in a collection
A for loop runs its body once per item in a list, binding a loop variable to each value in turn โ no manual counting required.
countries = ["Kenya", "Ghana", "Peru"]
for country in countries:
print(country)
# Kenya
# Ghana
# Peru
range() โ repeating a specific number of times
When you want to repeat an action a fixed number of times (not tied to a list), range() generates the sequence of numbers to loop over.
for i in range(5):
print(i)
# 0
# 1
# 2
# 3
# 4
# range(start, stop) โ customise where it begins
for i in range(2, 5):
print(i) # 2, 3, 4
while loops โ repeating until a condition changes
A while loop keeps running as long as its condition stays True. Unlike a for loop, nothing automatically ends it โ you must change the checked value yourself inside the loop body, or it runs forever.
count = 0
while count < 5:
print(count)
count = count + 1 # without this line, the loop never ends!
# 0
# 1
# 2
# 3
# 4
break and continue
break exits a loop immediately and completely. continue skips only the rest of the current pass and moves on to the next item. (Population figures are in millions, to keep the numbers easy to read.)
countries = [
{"name": "Norway", "population": 5},
{"name": "Kenya", "population": 54},
{"name": "India", "population": 1428},
]
# break โ stop as soon as we find what we need
for c in countries:
if c["population"] > 100:
print("Found one:", c["name"])
break
# continue โ skip small countries, but keep checking the rest
for c in countries:
if c["population"] < 10:
continue
print(c["name"])
4. Lab
What you will build
A file called loops.py.
Step-by-step instructions
Create the file and loop over a list of country names
# loops.py
countries = ["Kenya", "Ghana", "Peru", "Japan"]
for country in countries:
print(country)
Use range() to print numbered positions
for i in range(len(countries)):
print(i, countries[i])
Write a while loop that counts down from 5
Make sure the loop actually terminates.
count = 5
while count > 0:
print(count)
count = count - 1
print("Liftoff!")
Use break to stop as soon as a target is found
target = "Peru"
for country in countries:
if country == target:
print("Found", target)
break
print("Checked", country, "- not a match")
Use continue to skip items that do not match a condition
for country in countries:
if len(country) < 5:
continue
print(country, "has 5 or more letters")
5. Expected Files Changed
| File | Action | Why |
|---|---|---|
loops.py |
Created | Demonstrates for loops, range(), while loops, break, and continue. |
docs/sessions/session-04/index.html |
Created | This session document โ Layer 0 gate. |
6. Commit Checkpoint
Once the lab is complete and you can explain every line, make this exact commit:
git add loops.py docs/sessions/session-04/index.html
git commit -m "session-04: repeat actions with for/while loops, break, and continue"
7. Code Review Checklist
Go through your code line by line and check each item:
8. Post-Coding Quiz
Same 5 questions. Take it again now that you have written and run the code. You need 4/5 to mark this session complete.
Given countries = ["Kenya", "Ghana", "Peru"] and the following code, what prints?
for country in countries:
print(country)
for ... in loop runs its body once for every item in the list, binding country to each value in turn. Since the body is print(country), each name prints on its own line.What does range(5) produce when looped over?
range(5) produces 5 numbers starting at 0 and stopping BEFORE 5: 0, 1, 2, 3, 4. This "starts at 0, stops before the given number" behavior matches how list indexing works, which is why it is the default.What is the danger of writing while count < 10: without ever changing count inside the loop body?
while loop keeps running as long as its condition is True. If nothing inside the loop body ever changes the value being checked, the condition never becomes False, and the loop never ends โ you must update the checked value yourself, usually near the end of the loop body.Given a loop searching for the first country with population over 100 million, what does break do once it is found?
break exits the loop immediately and completely โ useful once you have found what you were looking for and have no reason to keep checking the remaining items.Given the following, what does continue do for a country with a small population?
for c in countries:
if c["population"] < 10:
continue
print(c["name"])
continue skips only the remainder of the current iteration's body and moves the loop on to the next item โ unlike break, the loop keeps going, it just skips printing for items matching the condition.9. Reflection Questions
Think through these after the post-quiz. No right answer โ they are for discussion.
- What would you observe on screen if you accidentally created an infinite while loop? How would you know something was wrong, and how would you stop it?
- Why does break stop the ENTIRE loop, while continue only skips the current pass? Can you think of a scenario where you would want one but not the other?
- Rewrite the range()-based numbered loop using enumerate(countries) instead (look up what it does). Which version is clearer to you right now?
- Why is a for loop generally preferred over a while loop when you already know exactly what collection you are iterating over?
10. What Breaks If This Knowledge Is Missing?
- Every data-processing session in this entire curriculum: From Session 05 (Dictionaries) forward through the entire Country Explorer project, looping over collections of data is the single most repeated operation in the whole course. If a for loop does not feel completely automatic, everything ahead will be much harder than it needs to be.
- Infinite loops in real programs: A while loop whose condition never becomes False will hang a real program indefinitely โ this is a genuine, common bug, not just a classroom exercise, and recognising the risk now will save you real debugging time later.
11. What We Learned
Python concept mastered: Repeating actions with for loops, range(), while loops, and controlling loop flow with break and continue.
Unlocks: You now have every fundamental building block โ variables, types, operators, conditionals, and loops โ needed to read and write real Python programs. Layer 0 is complete.
Next session: Session 05 โ Dictionaries. Layer 1 begins. We start working with Python's most important data structure: the dictionary โ and everything from here builds toward a real, tested, deployed application.