for name in ["Alice", "Bob", "Carol"]:
print(f"Hello, {name}!")
Read it as: "for every name in this list, do the indented stuff." Three names → three greetings.
for i in range(5):
print(i)
# 0
# 1
# 2
# 3
# 4
range(5) = 0, 1, 2, 3, 4. (Stops before 5 — Python's standard half-open style.)
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8
items = ["bread", "milk", "eggs"]
for i, item in enumerate(items, start=1):
print(f"{i}. {item}")
# 1. bread
# 2. milk
# 3. eggs
prices = {"bread": 3.50, "milk": 2.10, "eggs": 5.00}
for product, price in prices.items():
print(f"{product}: ${price}")
break — stop the loop entirely.continue — skip the rest of this iteration; jump to the next item.for n in range(20):
if n % 2 != 0: # odd
continue
if n > 12:
break
print(n)
# 0 2 4 6 8 10 12
invoices = [
{"customer": "Acme", "amount": 1200},
{"customer": "Beta", "amount": 800},
{"customer": "Acme", "amount": 300},
{"customer": "Gamma", "amount": 1500},
]
total = 0
for inv in invoices:
total += inv["amount"]
print(total) # 3800
total += inv["amount"] is shorthand for total = total + inv["amount"].
sum(inv["amount"] for inv in invoices). We meet that pattern (a "generator expression") later.
If you're using pandas, you almost never need a manual loop. df["amount"].sum() beats writing out the loop in both speed and clarity. We'll see this everywhere from Module 9 onwards.
for x in collection: — visit every item.range(n) — loop n times.enumerate() when you also need the index.break stops the loop; continue skips to the next item.For numbers 1 to 30: print "Fizz" if divisible by 3, "Buzz" if divisible by 5, "FizzBuzz" if both, otherwise the number. Classic interview question. You now know enough to write it.