Python Loops: for, while, break, continue, and enumerate
What you’ll learn
Section titled “What you’ll learn”- How to iterate over sequences and other iterables with
for. - How to generate and loop over number ranges with
range(). - How to write
whileloops and control them withbreakandcontinue. - How to pair values with their positions using
enumerate()andzip(). - How nested loops work, and when to avoid them.
- How Python’s loop
elseclause works and when it is useful. - How to choose between
forandwhilefor a given task.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or newer installed (
python --version). - Familiarity with variables, lists, and strings.
Step 1 — Iterating over iterables with for
Section titled “Step 1 — Iterating over iterables with for”A for loop walks through the items of any iterable — a list, tuple, string, dict, set, or anything that can produce one item at a time. Each iteration binds the loop variable to the next item. You almost never need a manual counter in Python because the loop gives you the item directly.
orders = ["ORD-001", "ORD-002", "ORD-003"]
for order_id in orders: print(f"Processing {order_id}")# Processing ORD-001# Processing ORD-002# Processing ORD-003Iterating over a dict walks its keys by default; use .items() to get both the key and the value. Strings iterate one character at a time.
order = {"id": "ORD-001", "customer": "BensonCo", "amount": 149.99}
for key, value in order.items(): print(f"{key} = {value}")# id = ORD-001# customer = BensonCo# amount = 149.99
for char in "ORD-001": print(char, end=" ")# O R D - 0 0 1Verify: Add print("done") after the loop. It runs exactly once, after all items are processed, which confirms the loop completed normally.
Step 2 — Counting with range()
Section titled “Step 2 — Counting with range()”range() produces a sequence of numbers on demand without building a list in memory. range(n) yields 0 through n - 1, range(a, b) yields a through b - 1, and range(a, b, step) lets you skip or count backward. Use it when the iteration is “do this N times” or when you need the index itself.
# Three months of data: months 1, 2, 3for month in range(1, 4): print(f"Month {month}")# Month 1# Month 2# Month 3
# Even line-item numbers only, stepping by 2for line_no in range(2, 11, 2): print(line_no)# 2# 4# 6# 8# 10Verify: Print list(range(1, 4)). It should show [1, 2, 3], confirming range stops before the end value.
Step 3 — Repeating with while
Section titled “Step 3 — Repeating with while”A while loop runs as long as its condition is true. Use it when you do not know how many iterations you need up front, such as retrying a flaky network call or draining a queue. The condition is checked before each iteration, so the body may run zero times.
retries = 0max_retries = 3connected = False
while not connected and retries < max_retries: print(f"Attempt {retries + 1}") # pretend the call usually fails until the third try retries += 1 if retries == 3: connected = True
print("connected" if connected else "gave up")# Attempt 1# Attempt 2# Attempt 3# connectedVerify: Change max_retries to 0. The body should never run and the program should print gave up, which confirms the loop is guarded and cannot spin forever.
Step 4 — Controlling flow with break and continue
Section titled “Step 4 — Controlling flow with break and continue”break exits the loop immediately. continue skips the rest of the current iteration and jumps to the next one. Both work with for and while. Use break to stop early when you have found what you need, and continue to skip items that do not interest you.
# Stop at the first shipped orderorder_ids = ["ORD-001", "ORD-002", "ORD-003"]statuses = ["pending", "pending", "shipped"]
for i in range(len(order_ids)): if statuses[i] == "shipped": print(f"First shipped order is {order_ids[i]}") break# First shipped order is ORD-003
# Skip pending orders, process the restfor order_id, status in zip(order_ids, statuses): if status == "pending": continue print(f"Handling non-pending {order_id} ({status})")# Handling non-pending ORD-003 (shipped)Verify: Remove the break and confirm the loop now prints a match for every shipped order instead of just the first one. That confirms break was what stopped the scan early.
Step 5 — Pairing items with enumerate() and zip()
Section titled “Step 5 — Pairing items with enumerate() and zip()”enumerate() yields (index, value) pairs so you avoid tracking a counter by hand. zip() walks two or more iterables in lockstep, stopping at the shortest one. Together they replace the common for i in range(len(...)) pattern with clearer code.
items = ["keyboard", "mouse", "monitor"]
for index, name in enumerate(items, start=1): print(f"Line {index}: {name}")# Line 1: keyboard# Line 2: mouse# Line 3: monitor
quantities = [2, 5, 1]prices = [49.99, 19.99, 299.00]
for qty, price in zip(quantities, prices): print(f"${qty * price:.2f}")# $99.98# $99.95# $299.00Verify: Add a fourth quantity but only three prices. The loop should still print exactly three lines because zip stops at the shortest input.
Step 6 — Nested loops
Section titled “Step 6 — Nested loops”A loop inside a loop lets you process every combination of two sequences, such as every order against every shipping zone. Nested loops are clear but expensive: the total work is the product of the lengths, so a million-item outer loop times a thousand-item inner loop is a billion iterations. When you find yourself nesting three or more levels, reach for a dict lookup or a comprehension instead.
orders = ["ORD-001", "ORD-002"]zones = ["west", "east", "central"]
for order_id in orders: for zone in zones: print(f"{order_id} -> {zone}")# ORD-001 -> west# ORD-001 -> east# ORD-001 -> central# ORD-002 -> west# ORD-002 -> east# ORD-002 -> centralVerify: The output should have exactly len(orders) * len(zones) lines, here six. Counting the printed lines confirms every combination was visited once.
Step 7 — The loop else clause
Section titled “Step 7 — The loop else clause”Python gives loops an else block that runs only when the loop finishes normally, without hitting break. This is a Python-specific feature that removes the need for a “found” flag. It is most useful inside a function that searches for something: break when you find it, and put the “not found” handling in else.
order_ids = ["ORD-001", "ORD-002", "ORD-003"]target = "ORD-009"
for order_id in order_ids: if order_id == target: print(f"Found {target}") breakelse: # runs only because the loop never hit break print(f"{target} is not in the list")# ORD-009 is not in the listVerify: Set target = "ORD-002" and run again. The else block should not print this time, because break ran on the match.
Complete working example
Section titled “Complete working example”Save as loops_demo.py and run with python loops_demo.py (Python 3.9+):
"""OrdersPortal: process pending orders, retry shipping, and report."""
orders = [ {"id": "ORD-001", "status": "pending", "items": ["keyboard", "mouse"]}, {"id": "ORD-002", "status": "shipped", "items": ["monitor"]}, {"id": "ORD-003", "status": "pending", "items": ["cable", "adapter", "stand"]},]
# Ship every pending order, retrying up to 3 times eachfor order in orders: if order["status"] != "pending": continue
attempts = 0 while attempts < 3: attempts += 1 print(f"{order['id']}: shipping attempt {attempts}") if attempts == 3: # pretend the carrier accepts on the last try order["status"] = "shipped" break
# Count line items across all orders with enumerate for readable line numberstotal_items = 0for line_no, order in enumerate(orders, start=1): total_items += len(order["items"]) print(f"Line {line_no}: {order['id']} has {len(order['items'])} item(s)")
print(f"All orders: {orders}")print(f"Total line items: {total_items}")ORD-001: shipping attempt 1ORD-001: shipping attempt 2ORD-001: shipping attempt 3ORD-003: shipping attempt 1ORD-003: shipping attempt 2ORD-003: shipping attempt 3Line 1: ORD-001 has 2 item(s)Line 2: ORD-002 has 1 item(s)Line 3: ORD-003 has 3 item(s)All orders: [{'id': 'ORD-001', 'status': 'shipped', 'items': ['keyboard', 'mouse']}, {'id': 'ORD-002', 'status': 'shipped', 'items': ['monitor']}, {'id': 'ORD-003', 'status': 'shipped', 'items': ['cable', 'adapter', 'stand']}]Total line items: 6Common mistakes
Section titled “Common mistakes”while True:with no reliable exit. If the condition that should triggerbreaknever becomes true, the loop runs forever. Add an explicit, bounded condition or a maximum-iteration guard.- Modifying a list while iterating over it. Adding or removing items during iteration shifts indices and skips or duplicates items. Iterate over a copy:
for x in list(my_orders):. - Using
for i in range(len(seq)):just to index. Preferfor item in seq:for the value, orenumerate(seq)when you also need the index. - Forgetting
zipstops at the shortest iterable. Mismatched lengths silently drop the extra items. Useitertools.zip_longestwhen you need to keep the extras. - Confusing
elseon a loop withelseonif. A loopelseruns when the loop completes withoutbreak, not when the condition is false.
Choosing for vs while
Section titled “Choosing for vs while”Reach for for when you know what you are walking over — a collection or a fixed range of numbers. Reach for while when the number of repetitions depends on a condition you check each time, such as retrying until success or draining a queue. If you can write the loop as for x in iterable:, you usually should.
Next steps
Section titled “Next steps”- Control Flow tutorial —
if,for,while, and comprehensions in the step-by-step course - Comprehensions tutorial — build lists and dicts from loops
- Iterators and generators — what “iterable” really means
Related pages
Section titled “Related pages”- Conditionals — branching with
if,elif, andelse - Lists — the most common iterable
- Dictionaries — iterating over keys, values, and items
- enumerate() — index-and-value pairing in depth
- zip() — walking iterables in parallel