for loops
A for loop repeats a block of code once for each item in a collection.
Used in 129 lessons of the course, from 00.01.
A for loop walks over anything iterable (a list, a string, a dict, a range) and, on each pass, stores the next item in a name you choose.
for name in names:
print(name)
Read it as: "for each name in names, do this". The line ends with : and the body is indented; everything indented repeats on every pass.
It is written this way because you don't keep track of positions or indexes: Python hands you the items one at a time. Fewer counters, fewer mistakes.
The course uses it everywhere, starting in lesson 00.01: for number, term in enumerate(quiz_terms, start=1):. Each pass hands over two values at once (a number and a term), and the for splits them into two names with unpacking.
Reach for it when: you want to do the same thing with every item in a collection, or repeat something a known number of times.
Examples
Common mistake
for n in 5:
print(n)Why: An integer is not iterable; the for needs a collection that yields items.
How to write it: Use range(5) to repeat five times: for n in range(5):.
Common mistake
prices = {"a": 1, "b": 2}
for item in prices:
print(item)Why: Looping over a dict gives only the keys, not the values.
How to write it: Use prices.items() with for key, value in prices.items(): to get both.
