Lesson 60 +10 XP

For Loops

A for loop in Python iterates over a sequence, not by counting.

Loop over a list


python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)

Loop over a string


python
for x in "banana":
    print(x)

### b, a, n, a, n, a

Loop over a range

range() produces a sequence of numbers:


python
for x in range(6):
    print(x)

### 0, 1, 2, 3, 4, 5

Range with start and end


python
for x in range(2, 6):
    print(x)

### 2, 3, 4, 5

Range with a step


python
for x in range(2, 30, 3):
    print(x)

2, 5, 8, 11, ...

break and continue

They work the same as in while loops:


python
for x in fruits:
    if x == "banana":
        break
    print(x)

### apple only
for x in fruits:
    if x == "banana":
        continue
    print(x)

### skips banana

else on a for loop

Runs after the loop finishes, unless break stopped it:


python
for x in range(3):
    print(x)
else:
    print("Loop finished!")

Nested loops


python
adj = ["red", "big"]
fruits = ["apple", "banana"]
for a in adj:
    for f in fruits:
        print(a, f)

TL;DR

  • for x in sequence: iterates items, not indexes.
  • range() makes number sequences (start, end, step).
  • break exits; continue skips; else runs on natural end.
  • Loops nest inside each other.