# For & While Loops

> Master iteration in Python through for and while loops, index-free enumeration, early loop exits, and Python's unique for-else clause.

Subject: Python | Lesson 4 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/loops
Previous: [Conditionals & Truthy Logic](https://codewithanimation.in/python/if-else.md) | Next: [Lists & Slicing](https://codewithanimation.in/python/lists.md)

## The Python Iteration Protocol

In Python, `for` loops do not use the classic C-style index counter (`for (int i=0; i<n; i++)`). Instead, Python's `for` loop iterates directly over any iterable object - such as lists, strings, tuples, dictionaries, or generators - fetching elements one by one.

A `while` loop repeatedly executes its block as long as its condition remains truthy. It is primarily used when the number of iterations is unknown in advance, such as polling a connection or processing a queue.

## The Power of for ... else

Python provides a distinctive feature rarely found in other languages: an `else` block attached directly to a `for` or `while` loop.

The `else` clause executes if and only if the loop finishes all iterations naturally, without encountering a `break` statement.

This pattern eliminates the need for messy boolean flag variables (such as `found = False`) when searching for an item in a sequence.

## Loop Control: break, continue & enumerate

The `break` statement immediately terminates the loop and jumps execution past the entire loop construct, bypassing any `else` block.

The `continue` statement skips the remainder of the current iteration and jumps directly to the next cycle.

When you need both the zero-based index and the element itself, never iterate over `range(len(items))`. Use the built-in `enumerate(items)` function: `for index, item in enumerate(items):`.

## Common mistake: The range(len(...)) Anti-Pattern

Writing `for i in range(len(items)): val = items[i]` is un-pythonic, harder to read, and slower. It creates unnecessary index lookups and can cause IndexError if the list is modified during iteration.

Always iterate directly over `for item in items:`. If you need numeric indices, use `enumerate()`.

## Tip: Custom Start Index in enumerate

The `enumerate()` function accepts an optional `start` parameter: `for position, name in enumerate(names, start=1):` gives 1-based human-friendly numbering out of the box.

## Try it: The Iteration Stepper & Else Gate

Step through a loop item by item. Test what happens to the trailing else block when the loop completes naturally versus when a break is triggered early.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/loops

## Check yourself

### Question 1

Under what condition does the `else` block of a `for ... else` loop execute?

- A. When the loop completes all iterations without encountering a break statement.
- B. Whenever the loop body encounters an error or exception.
- C. Every time the loop finishes an iteration cycle.

Correct answer: A

A loop's `else` block runs only if the loop ran to completion without hitting an explicit `break`.

- Why not B: Incorrect. Exceptions are handled by try/except blocks, not loop else blocks.
- Why not C: Incorrect. The else block only runs once at the very end of the loop.

### Question 2

What is the recommended Pythonic way to access both the index and value in a loop?

- A. for i, item in enumerate(items):
- B. for i in range(len(items)): item = items[i]
- C. for item in items: i = items.index(item)

Correct answer: A

The built-in `enumerate()` function yields index-value pairs efficiently without index lookups or search overhead.

- Why not B: Incorrect. range(len(...)) is considered an anti-pattern in Python.
- Why not C: Incorrect. items.index() performs an O(n) search on every iteration and breaks on duplicates.

### Question 3

What happens when `continue` is executed inside a loop?

- A. The rest of the current iteration is skipped, and the loop advances to the next item.
- B. The entire loop is terminated immediately.
- C. The loop restarts from index 0.

Correct answer: A

`continue` immediately stops the current iteration and jumps to the next cycle of the loop.

- Why not B: Incorrect. That is the role of break, not continue.
- Why not C: Incorrect. The loop does not restart; it advances to the next item.

## Remember this

- Python for loops iterate directly over elements, not numeric indexes.
- Use enumerate(items) whenever both index and item are required.
- break terminates the entire loop immediately; continue skips to the next cycle.
- A loop's else block executes only if the loop finished without encountering a break.
- Avoid the range(len(items)) anti-pattern.
