python-for-j277 / control-flow · Lesson 07
Lesson 07 — Control flow
Iteration: For-each Loops
Step through every item in a collection, one at a time.
A for-each loop visits each item in a collection in turn. You give it a collection, and it hands you one item at a time.
Looping over the characters in a string
word = "code"
for letter in word:
print(letter)Output
c o d e
How it works
for letter in wordmeans 'take each character ofword, one at a time, and call itletter'.- The indented line runs once per character.
letterholds a different character on each pass: first"c", then"o", and so on.
Looping over a list of items
A list is a collection of values inside square brackets. There is much more on lists soon — for now we just loop through one.
names = ["Ava", "Ben", "Cara"]
for name in names:
print("Hello", name)Output
Hello Ava Hello Ben Hello Cara
How it works
- A list holds several values inside square brackets, separated by commas.
- The loop gives you each value in turn, storing it in
name. - The body runs three times — once for each name in the list.
Doing a calculation for each item
prices = [3, 5, 2]
total = 0
for price in prices:
total = total + price
print("Total:", total)Output
Total: 10
How it works
totalstarts at 0 before the loop.- Each pass adds the current
pricetototal. - After visiting every item,
totalholds the sum of the list.
When to use itUse a for-each loop when you want to do the same thing to every item in a collection.
What you have learned
- A for-each loop visits each item in a collection in turn.
- It works on strings (character by character) and lists (item by item).
- The loop variable holds a different item on each pass.
- The number of repeats matches the number of items.