Lesson 9 / 47

Loops

for over sequences, while, and comprehensions.

for + range

for iterates any sequence; range generates numbers.

for fruit in ["apple", "banana"]:
    print(fruit)

for i in range(1, 10, 2):
    print(i)          # 1 3 5 7 9

Comprehensions

Build a list in one readable line.

squares = [n * n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]

Quick check: When does a loop's `else` block run?

  • Every time the loop ends
  • Only if the loop finished without `break`
  • Only if the loop never ran
Answer

Only if the loop finished without `break` — A `break` skips the loop's `else`.