Module 3 · Loops in Python · Lesson 5 of 6
The for loop
Where a while loop repeats until a condition changes, a for loop walks through a ready-made sequence, one item at a time — and stops automatically when it runs out. No counter to manage, no condition to get wrong.
for fruit in ["apple", "banana", "cherry"]: print(fruit)
Read it almost as English: for fruit in the list, do this. Each time round, the loop variable — fruit — is set to the next item, and the indented body runs with it. A for loop will happily step through a list, the characters of a string, or a range() of numbers:
Pairing for with range() is the classic “do this N times” pattern — and it's exactly the loop from the home page: a counter walking range(5), adding each number to a running total.
loop.pyrunningtotal = 0for i in range(5):total += i
Like while, a for loop can carry an else that runs when the loop finishes without a break. It's a tidy way to say “I went through everything and didn't find it”:
Between for, while, range() and break/continue, you can now express almost any kind of repetition. A quick quiz to seal it in.