Learning navigation

Code with Animation

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.

Python7 min readConcept 4 of 24

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):.

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.

# Iterating with enumerate:
items = ["python", "fastapi", "django", "pytest"]
# The for ... else loop:
for idx, item in enumerate(items):
if item == "trigger_break":
break # Skips else!
process(item)
else:
print("Complete!")
CURRENT ITERATION: idx = 0ACTIVEitem = "python"idx: 0"python"idx: 1"fastapi"idx: 2"django"idx: 3"pytest"else: CLAUSE RELAY STATUS... AWAITING COMPLETION ...Currently at item 1 of 4.else will execute if loop finishes with 0 breaks.
★

Python Pattern: Use for ... else instead of messy boolean flags (like found = False). If the search ends without a break, the else clause executes the fallback cleanly.

Python for loops iterate directly over items. The trailing else block executes only if the loop runs to natural completion without a break.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Under what condition does the `else` block of a `for ... else` loop execute?
  2. 2What is the recommended Pythonic way to access both the index and value in a loop?
  3. 3What happens when `continue` is executed inside a loop?

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.

Done with this concept?

Mark it complete to track your progress. No login needed.