# Loops — Python Fundamentals: From Basics to Async

Source: https://www.skillbyai.com/en/python/py-loops

> Repeat work with for and while loops, range and loop else clauses, and build lists with comprehensions.

## for + range

`for` iterates any sequence; `range` generates numbers.

```python
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.

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

**Quiz:** When does a loop's `else` block run?

- [ ] Every time the loop ends
- [ ] Only if the loop never ran
- [ ] Only when an exception is raised
- [x] Only if the loop finished without `break`

*Answer:* Only if the loop finished without `break`. A `break` skips the loop's `else`.
