> For the complete documentation index, see [llms.txt](https://ricardomol.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ricardomol.gitbook.io/notes/backend/python/for-else.md).

# For - else

## `else` Clause

**Executes after the loop completes normally.** Ie., **the loop did not encounter a `break`**&#x73;tatement.

## Common use case

Run a loop to search for an item. If the item is found, we break out of the loop using the `break` statement.&#x20;

2 scenarios in which the loop may end:

1. when the **item is found and `break`** is encountered.
2. The **loop ends without encountering a `break`** statement.

**We may want to know which one of these is the reason for a loop’s completion. One method is to set a flag and then check it once the loop ends. Another is to use the `else` clause**.

## Bluprint

```python
for item in container:
    if search_something(item):
        # Found it!
        process(item)
        break
else:
    # Didn't find anything..
    not_found_in_container()
```

## Example

Consider this example: It finds factors for numbers between 2 to 10.:

```python
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n/x)
            break
```

We can **add an additional `else`block which catches the numbers which have no factors and are therefore prime** numbers:

```python
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print( n, 'equals', x, '*', n/x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')
```
