For every item
A for loop runs its block once per item in a sequence.
colors = ["red", "green", "blue"]
for color in colors:
print(color)
color is the loop variable: it holds the current item on each trip around. Name it for one thing — for student in students reads far better than for x in students.
Counting with range()
for number in range(5):
print(number) # 0 1 2 3 4 — range stops before the end
for number in range(1, 4):
print(number) # 1 2 3 — start, then stop before 4
Building a total
This pattern shows up everywhere:
prices = [2.5, 3, 4.25]
total = 0
for price in prices:
total = total + price
print(total) # 9.75
Start the total at 0, add each item inside the loop, and print after the loop finishes. Indentation is what tells Python which lines are inside the loop.