for and while loops
Overview
Python has two loop forms. A for loop iterates over any iterable — a list, string, range, dict, or file — consuming it item by item: for record in db_results: process(record) A while loop runs as long as its condition is truthy: retries = 0 while retries < 3: retries += 1 Three built-ins that make for loops more powerful in practice: range(n) produces integers 0..n-1 for index-counting; enumerate(items) yields (index, value) pairs so you don't need a separate counter; dict.items() yields (key, value) pairs for iterating over every entry in a dict. Think of for as 'do this once per item in the collection' and while as 'keep going until a condition flips'.
Loops are the mechanism behind every batch operation in real backends — processing rows, retrying HTTP requests, building response payloads from multiple sources. Knowing enumerate() and dict.items() eliminates the need for error-prone manual index management.
Where used: FastAPI batch endpoint handlers, ETL pipelines, config and env-var processing
Why learn this
- Processing lists of database records, API responses, or config entries without manual index tracking via enumerate()
- Writing correct retry logic in HTTP clients and database reconnection loops with while
Code walkthrough
config = {'host': 'localhost', 'port': 5432, 'db': 'main'}
for key, value in config.items():
print(f'{key}={value}')
Focus: config.items() yields each key-value pair as a tuple; the for loop unpacks it into key and value — no index variable needed.
Common mistakes
- Mutating a list while iterating over it: Removing or inserting items in a list during a for loop skips or repeats elements. Fix: iterate over a copy (for item in items[:]:) or collect changes in a separate list.
- Using range(len(items)) instead of enumerate(): for i in range(len(items)): items[i] is verbose and error-prone. for i, item in enumerate(items): is cleaner and idiomatic.
- Forgetting that while True needs an explicit break: while True: is valid for event loops and retry loops, but omitting a break or return inside the loop creates an infinite loop.
Glossary
- iterable
- Any collection or data structure in Python that you can loop through one item at a time, like a list or a string, e.g. `for x in [1, 2, 3]`.
- idiomatic
- Writing code in a way that is natural, concise, and follows the widely accepted best practices of the programming language, e.g. `for i, item in enumerate(items)` instead of `for i in range(len(items))`.
Recall questions
- What is the difference between a for loop and a while loop?
- What does enumerate() give you that a plain for loop does not?
- How do you iterate over both keys and values of a dict simultaneously?
- What does range(n) produce?
Understanding checks
What is printed by this code?
1:A 2:B
The `enumerate` function yields the index and the value. The `start=1` argument changes the index counter to start at 1 instead of the default 0.
A developer writes `for key in my_dict.items():` and expects `key` to be a string. What will `key` actually be?
A tuple containing both the key and the value.
`dict.items()` yields `(key, value)` tuples. To get just the keys, iterate over the dict directly (`for key in my_dict:`). To get both, unpack them (`for k, v in my_dict.items():`).
Practice tasks
Fix the dictionary iteration
The `print_config` function attempts to print the key-value pairs of a dictionary. However, it is iterating over the dict incorrectly, resulting in `key` containing only the keys and `val` throwing an error. Modify the loop to correctly unpack the dictionary's items.
Challenge
Retry loop with backoff counter
Write fetch_with_retry(attempts) that simulates a failing request: it prints 'attempt <n>' for each try (1-based), and after exhausting all attempts prints 'failed after <n> attempts'. Use a while loop with a manual counter. Do not use range().
Continue learning
Previous: if/elif/else and Python truthiness
Previous: Primitive types: int, float, bool, str
Previous: Dynamic typing and type()
Next: break, continue, loop else clause
Next: List Comprehensions