Control Flow
Break and Continue
Loop Control
You're scanning a list of 10,000 products for item #4521. Once found, why keep
searching? break lets you exit immediately. Or you're processing orders but
want to skip cancelled ones - continue jumps to the next iteration.
Find first match (break)
Stop searching once you find what you're looking for.
numbers = [10, 25, 30, 42, 55, 60]
target = 42
found_index = -1
for i, num in enumerate(numbers):
print(f"Checking index {i}: {num}")
if num == target:
found_index = i
break
if found_index != -1:
print(f"Found {target} at index {found_index}")
else:
print(f"{target} not found")
# Without break, would check all elements unnecessarily
# With break, stops at first match
numbers = [10, 25, 30, 42, 55, 60]
target = 30
found_index = -1
for i, num in enumerate(numbers):
print(f"Checking index {i}: {num}")
if num == target:
found_index = i
break
if found_index != -1:
print(f"Found {target} at index {found_index}")
else:
print(f"{target} not found")
# Without break, would check all elements unnecessarily
# With break, stops at first match
numbers = [10, 25, 30, 42, 55, 60]
target = 99
found_index = -1
for i, num in enumerate(numbers):
print(f"Checking index {i}: {num}")
if num == target:
found_index = i
break
if found_index != -1:
print(f"Found {target} at index {found_index}")
else:
print(f"{target} not found")
# Without break, would check all elements unnecessarily
# With break, stops at first match
numbers ← [10, 25, 30, 42, 55, 60], target ← 42, found_index ← -1
1numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]2target→ 42 = 42 #@target=30, 9934found_index→ -1 = -15for i, num in enumerate(numbers):for i, num in enumerate(numbers):
pass 1 of 44found_index = -15for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):6 print(f"Checking index {i0}: {num10}")7 if num == target:outputChecking index 0: 10All 4 passes — pass 1 is the card above pass inumtargetfound_index1 0 10 — — 2 1 25 — — 3 2 30 — — 4 3 42 42 3 found_index ← 3
6print(f"Checking index {i}: {num}")7if num42 == target42:8 found_index→ 3 = i39 break #?break_exitif found_index != -1:
11if found_index3 != -1:12 print(f"Found {target42} at index {found_index3}")13else:outputFound 42 at index 3
numbers ← [10, 25, 30, 42, 55, 60], target ← 30, found_index ← -1
1numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]2target→ 30 = 3034found_index→ -1 = -15for i, num in enumerate(numbers):for i, num in enumerate(numbers):
pass 1 of 34found_index = -15for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):6 print(f"Checking index {i0}: {num10}")7 if num == target:outputChecking index 0: 10All 3 passes — pass 1 is the card above pass inumtargetfound_index1 0 10 — — 2 1 25 — — 3 2 30 30 2 found_index ← 2
6print(f"Checking index {i}: {num}")7if num30 == target30:8 found_index→ 2 = i29 breakif found_index != -1:
11if found_index2 != -1:12 print(f"Found {target30} at index {found_index2}")13else:outputFound 30 at index 2
numbers ← [10, 25, 30, 42, 55, 60], target ← 99, found_index ← -1
1numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]2target→ 99 = 9934found_index→ -1 = -15for i, num in enumerate(numbers):for i, num in enumerate(numbers):
pass 1 of 64found_index = -15for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):6 print(f"Checking index {i0}: {num10}")7 if num == target:outputChecking index 0: 10All 6 passes — pass 1 is the card above pass inumtarget1 0 10 — 2 1 25 — 3 2 30 — 4 3 42 — 5 4 55 — 6 5 60 99 else:
11if found_index != -1:12 print(f"Found {target} at index {found_index}")13else:14 print(f"{target99} not found")output99 not found
break exits the loop immediately. More efficient than checking all elements.
Skip invalid entries (continue)
Skip items that don't meet criteria without stopping the loop.
scores = [85, -1, 92, 0, 78, -5, 95] # -1 and -5 are invalid
total = 0
count = 0
print("Processing scores:")
for score in scores:
if score < 0:
print(f" Skipping invalid: {score}")
continue
print(f" Adding: {score}")
total += score
count += 1
print(f"Valid scores: {count}")
print(f"Sum: {total}")
if count > 0:
print(f"Average: {total // count}")
# Pythonic alternative: filter
valid_scores = [s for s in scores if s >= 0]
print(f"\nFiltered: {valid_scores}")
print(f"Average: {sum(valid_scores) // len(valid_scores)}")
scores ← [85, -1, 92, 0, 78, -5, 95], total ← 0, count ← 0
1scores→ [85, -1, 92, 0, 78, -5, 95] = [85, -1, 92, 0, 78, -5, 95] # -1 and -5 are invalid23total→ 0 = 04count→ 0 = 056print("Processing scores:")7for score in scores:outputProcessing scores:total ← 85, count ← 1
pass 1 of 76print("Processing scores:")7for score85 in scores[85, -1, 92, 0, 78, -5, 95]:8 if score < 0: #?skip_invalid9 print(f" Skipping invalid: {score}")10 continue11 print(f" Adding: {score85}")12 total→ 85 += score8513 count→ 1 += 1output Adding: 85All 7 passes — pass 1 is the card above pass scoretotalcount1 85 0 → 85 0 → 1 2 -1 — — 3 92 85 → 177 1 → 2 4 0 177 2 → 3 5 78 177 → 255 3 → 4 6 -5 — — 7 95 255 → 350 4 → 5 if score < 0: #?skip_invalid
pass 1 of 27for score in scores:8 if score-1 < 0: #?skip_invalid9 print(f" Skipping invalid: {score-1}")10 continue11 print(f" Adding: {score}")output Skipping invalid: -1if score < 0: #?skip_invalid
pass 2 of 27for score in scores:8 if score-5 < 0: #?skip_invalid9 print(f" Skipping invalid: {score-5}")10 continue11 print(f" Adding: {score}")output Skipping invalid: -5print(f"Valid scores: {count}")
15print(f"Valid scores: {count5}")16print(f"Sum: {total350}")17if count > 0:outputValid scores: 5 Sum: 350if count > 0:
16print(f"Sum: {total}")17if count5 > 0:18 print(f"Average: {total350 // count5}")outputAverage: 70valid_scores ← [85, 92, 0, 78, 95]
20# Pythonic alternative: filter21valid_scores→ [85, 92, 0, 78, 95] = [s for s in scores[85, -1, 92, 0, 78, -5, 95] if s >= 0]22print(f"\nFiltered: {valid_scores[85, 92, 0, 78, 95]}")23print(f"Average: {sum(valid_scores[85, 92, 0, 78, 95]) // len(valid_scores)}")output Filtered: [85, 92, 0, 78, 95] Average: 70
continue jumps to the next iteration, skipping the rest of the loop body.
Early exit on error
Stop processing if something goes wrong.
commands = ["load", "process", "error", "save", "exit"]
success = True
for cmd in commands:
print(f"Executing: {cmd}")
# Stop on error
if cmd == "error":
print("ERROR: Operation failed!")
success = False
break
print(" Done.")
if success:
print("All commands completed successfully.")
else:
print("Processing stopped due to error.")
commands = ["init", "run", "complete"]
success = True
for cmd in commands:
print(f"Executing: {cmd}")
# Stop on error
if cmd == "error":
print("ERROR: Operation failed!")
success = False
break
print(" Done.")
if success:
print("All commands completed successfully.")
else:
print("Processing stopped due to error.")
commands = ["start", "stop"]
success = True
for cmd in commands:
print(f"Executing: {cmd}")
# Stop on error
if cmd == "error":
print("ERROR: Operation failed!")
success = False
break
print(" Done.")
if success:
print("All commands completed successfully.")
else:
print("Processing stopped due to error.")
commands ← ['load', 'process', 'error', 'save', 'exit'], success ← True
1commands→ ['load', 'process', 'error', 'save', 'exit'] = ["load", "process", "error", "save", "exit"]2#@commands=["init", "run", "complete"], ["start", "stop"]34success→ True = Truefor cmd in commands:
pass 1 of 36for cmdload in commands['load', 'process', 'error', 'save', 'exit']:7 print(f"Executing: {cmdload}")8 9 # Stop on error10 if cmd == "error":11 print("ERROR: Operation failed!")12 success = False13 break14 15 print(" Done.")outputExecuting: load Done.All 3 passes — pass 1 is the card above pass cmdsuccess1 load — 2 process — 3 error False success ← False
9# Stop on error10if cmderror == "error":11 print("ERROR: Operation failed!")12 success→ False = False13 breakoutputERROR: Operation failed!else:
17if success:18 print("All commands completed successfully.")19else:20 print("Processing stopped due to error.")outputProcessing stopped due to error.
commands ← ['init', 'run', 'complete'], success ← True
1commands→ ['init', 'run', 'complete'] = ["init", "run", "complete"]23success→ True = Truefor cmd in commands:
pass 1 of 35for cmdinit in commands['init', 'run', 'complete']:6 print(f"Executing: {cmdinit}")7 8 # Stop on error9 if cmd == "error":10 print("ERROR: Operation failed!")11 success = False12 break13 14 print(" Done.")outputExecuting: init Done.All 3 passes — pass 1 is the card above pass cmdsuccess1 init — 2 run — 3 complete True if success:
16if successTrue:17 print("All commands completed successfully.")18else:outputAll commands completed successfully.
commands ← ['start', 'stop'], success ← True
1commands→ ['start', 'stop'] = ["start", "stop"]23success→ True = Truefor cmd in commands:
pass 1 of 25for cmdstart in commands['start', 'stop']:6 print(f"Executing: {cmdstart}")7 8 # Stop on error9 if cmd == "error":10 print("ERROR: Operation failed!")11 success = False12 break13 14 print(" Done.")outputExecuting: start Done.for cmd in commands:
pass 2 of 25for cmdstop in commands['start', 'stop']:6 print(f"Executing: {cmdstop}")7 8 # Stop on error9 if cmd == "error":10 print("ERROR: Operation failed!")11 success = False12 break13 14 print(" Done.")outputExecuting: stop Done.if success:
16if successTrue:17 print("All commands completed successfully.")18else:outputAll commands completed successfully.
Validate early and break if invalid - cleaner than deep nesting.
Process until sentinel
Process data until you encounter a special "stop" value.
# Data with sentinel value -1 marking end
data = [10, 20, 30, 40, -1, 50, 60]
print("Processing until sentinel (-1):")
total = 0
for value in data:
if value == -1:
print("Sentinel found, stopping.")
break
print(f"Processing: {value}")
total += value
print(f"Sum of processed values: {total}")
# Pythonic: itertools.takewhile
from itertools import takewhile
print("\nUsing takewhile:")
data2 = [10, 20, 30, 40, -1, 50, 60]
for value in takewhile(lambda x: x != -1, data2):
print(f"Processing: {value}")
total2 = sum(takewhile(lambda x: x != -1, data2))
print(f"Sum: {total2}")
# Data with sentinel value -1 marking end
data = [5, 10, 15, -1, 20]
print("Processing until sentinel (-1):")
total = 0
for value in data:
if value == -1:
print("Sentinel found, stopping.")
break
print(f"Processing: {value}")
total += value
print(f"Sum of processed values: {total}")
# Pythonic: itertools.takewhile
from itertools import takewhile
print("\nUsing takewhile:")
data2 = [10, 20, 30, 40, -1, 50, 60]
for value in takewhile(lambda x: x != -1, data2):
print(f"Processing: {value}")
total2 = sum(takewhile(lambda x: x != -1, data2))
print(f"Sum: {total2}")
# Data with sentinel value -1 marking end
data = [100, 200, 300, 400]
print("Processing until sentinel (-1):")
total = 0
for value in data:
if value == -1:
print("Sentinel found, stopping.")
break
print(f"Processing: {value}")
total += value
print(f"Sum of processed values: {total}")
# Pythonic: itertools.takewhile
from itertools import takewhile
print("\nUsing takewhile:")
data2 = [10, 20, 30, 40, -1, 50, 60]
for value in takewhile(lambda x: x != -1, data2):
print(f"Processing: {value}")
total2 = sum(takewhile(lambda x: x != -1, data2))
print(f"Sum: {total2}")
data ← [10, 20, 30, 40, -1, 50, 60], total ← 0
1# Data with sentinel value -1 marking end2data→ [10, 20, 30, 40, -1, 50, 60] = [10, 20, 30, 40, -1, 50, 60]3#@data=[5, 10, 15, -1, 20], [100, 200, 300, 400]45print("Processing until sentinel (-1):")6total→ 0 = 0outputProcessing until sentinel (-1):total ← 10
pass 1 of 58for value10 in data[10, 20, 30, 40, -1, 50, 60]:9 if value == -1: #?sentinel_check10 print("Sentinel found, stopping.")11 break12 print(f"Processing: {value10}")13 total→ 10 += value10outputProcessing: 10All 5 passes — pass 1 is the card above pass valuetotal1 10 0 → 10 2 20 10 → 30 3 30 30 → 60 4 40 60 → 100 5 -1 — if value == -1: #?sentinel_check
8for value in data:9 if value-1 == -1: #?sentinel_check10 print("Sentinel found, stopping.")11 break12 print(f"Processing: {value}")outputSentinel found, stopping.data2 ← [10, 20, 30, 40, -1, 50, 60]
15print(f"Sum of processed values: {total100}")1617# Pythonic: itertools.takewhile18from itertools import takewhile1920print("\nUsing takewhile:")21data2→ [10, 20, 30, 40, -1, 50, 60] = [10, 20, 30, 40, -1, 50, 60]22for value in takewhile(lambda x: x != -1, data2):outputSum of processed values: 100 Using takewhile:for value in takewhile(lambda x: x != -1, data2):
pass 1 of 421data2 = [10, 20, 30, 40, -1, 50, 60]22for value10 in takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]):23 print(f"Processing: {value10}")outputProcessing: 10All 4 passes — pass 1 is the card above pass value1 10 2 20 3 30 4 40 total2 ← 100
25total2→ 100 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]))26print(f"Sum: {total2100}")outputSum: 100
data ← [5, 10, 15, -1, 20], total ← 0
1# Data with sentinel value -1 marking end2data→ [5, 10, 15, -1, 20] = [5, 10, 15, -1, 20]34print("Processing until sentinel (-1):")5total→ 0 = 0outputProcessing until sentinel (-1):total ← 5
pass 1 of 47for value5 in data[5, 10, 15, -1, 20]:8 if value == -1:9 print("Sentinel found, stopping.")10 break11 print(f"Processing: {value5}")12 total→ 5 += value5outputProcessing: 5All 4 passes — pass 1 is the card above pass valuetotal1 5 0 → 5 2 10 5 → 15 3 15 15 → 30 4 -1 — if value == -1:
7for value in data:8 if value-1 == -1:9 print("Sentinel found, stopping.")10 break11 print(f"Processing: {value}")outputSentinel found, stopping.data2 ← [10, 20, 30, 40, -1, 50, 60]
14print(f"Sum of processed values: {total30}")1516# Pythonic: itertools.takewhile17from itertools import takewhile1819print("\nUsing takewhile:")20data2→ [10, 20, 30, 40, -1, 50, 60] = [10, 20, 30, 40, -1, 50, 60]21for value in takewhile(lambda x: x != -1, data2):outputSum of processed values: 30 Using takewhile:for value in takewhile(lambda x: x != -1, data2):
pass 1 of 420data2 = [10, 20, 30, 40, -1, 50, 60]21for value10 in takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]):22 print(f"Processing: {value10}")outputProcessing: 10All 4 passes — pass 1 is the card above pass value1 10 2 20 3 30 4 40 total2 ← 100
24total2→ 100 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]))25print(f"Sum: {total2100}")outputSum: 100
data ← [100, 200, 300, 400], total ← 0
1# Data with sentinel value -1 marking end2data→ [100, 200, 300, 400] = [100, 200, 300, 400]34print("Processing until sentinel (-1):")5total→ 0 = 0outputProcessing until sentinel (-1):total ← 100
pass 1 of 47for value100 in data[100, 200, 300, 400]:8 if value == -1:9 print("Sentinel found, stopping.")10 break11 print(f"Processing: {value100}")12 total→ 100 += value100outputProcessing: 100All 4 passes — pass 1 is the card above pass valuetotal1 100 0 → 100 2 200 100 → 300 3 300 300 → 600 4 400 600 → 1000 data2 ← [10, 20, 30, 40, -1, 50, 60]
14print(f"Sum of processed values: {total1000}")1516# Pythonic: itertools.takewhile17from itertools import takewhile1819print("\nUsing takewhile:")20data2→ [10, 20, 30, 40, -1, 50, 60] = [10, 20, 30, 40, -1, 50, 60]21for value in takewhile(lambda x: x != -1, data2):outputSum of processed values: 1000 Using takewhile:for value in takewhile(lambda x: x != -1, data2):
pass 1 of 420data2 = [10, 20, 30, 40, -1, 50, 60]21for value10 in takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]):22 print(f"Processing: {value10}")outputProcessing: 10All 4 passes — pass 1 is the card above pass value1 10 2 20 3 30 4 40 total2 ← 100
24total2→ 100 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]))25print(f"Sum: {total2100}")outputSum: 100
Sentinel values signal "end of data" - common in file and stream processing.
For-else (Python unique!)
Python's for-else executes else only if loop completes without break.
# Python's unique for-else construct
numbers = [10, 25, 30, 42, 55, 60]
target = 42
# for-else: else runs only if loop completes WITHOUT break
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
break
else:
print(f"{target} not found")
# Equivalent without for-else
print("\n--- Without for-else ---")
found = False
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
found = True
break
if not found:
print(f"{target} not found")
# Practical: search with validation
print("\n--- Practical example ---")
users = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True},
]
search_id = 2
for user in users:
if user["id"] == search_id:
print(f"Found user: {user['name']}")
break
else:
print(f"User {search_id} not found")
# Python's unique for-else construct
numbers = [10, 25, 30, 42, 55, 60]
target = 30
# for-else: else runs only if loop completes WITHOUT break
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
break
else:
print(f"{target} not found")
# Equivalent without for-else
print("\n--- Without for-else ---")
found = False
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
found = True
break
if not found:
print(f"{target} not found")
# Practical: search with validation
print("\n--- Practical example ---")
users = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True},
]
search_id = 2
for user in users:
if user["id"] == search_id:
print(f"Found user: {user['name']}")
break
else:
print(f"User {search_id} not found")
# Python's unique for-else construct
numbers = [10, 25, 30, 42, 55, 60]
target = 99
# for-else: else runs only if loop completes WITHOUT break
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
break
else:
print(f"{target} not found")
# Equivalent without for-else
print("\n--- Without for-else ---")
found = False
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
found = True
break
if not found:
print(f"{target} not found")
# Practical: search with validation
print("\n--- Practical example ---")
users = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True},
]
search_id = 2
for user in users:
if user["id"] == search_id:
print(f"Found user: {user['name']}")
break
else:
print(f"User {search_id} not found")
# Python's unique for-else construct
numbers = [10, 25, 30, 42, 55, 60]
target = 42
# for-else: else runs only if loop completes WITHOUT break
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
break
else:
print(f"{target} not found")
# Equivalent without for-else
print("\n--- Without for-else ---")
found = False
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
found = True
break
if not found:
print(f"{target} not found")
# Practical: search with validation
print("\n--- Practical example ---")
users = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True},
]
search_id = 1
for user in users:
if user["id"] == search_id:
print(f"Found user: {user['name']}")
break
else:
print(f"User {search_id} not found")
# Python's unique for-else construct
numbers = [10, 25, 30, 42, 55, 60]
target = 42
# for-else: else runs only if loop completes WITHOUT break
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
break
else:
print(f"{target} not found")
# Equivalent without for-else
print("\n--- Without for-else ---")
found = False
for i, num in enumerate(numbers):
if num == target:
print(f"Found {target} at index {i}")
found = True
break
if not found:
print(f"{target} not found")
# Practical: search with validation
print("\n--- Practical example ---")
users = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True},
]
search_id = 99
for user in users:
if user["id"] == search_id:
print(f"Found user: {user['name']}")
break
else:
print(f"User {search_id} not found")
numbers ← [10, 25, 30, 42, 55, 60], target ← 42
1# Python's unique for-else construct2numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]3target→ 42 = 42 #@target=30, 99for i, num in enumerate(numbers):
pass 1 of 45# for-else: else runs only if loop completes WITHOUT break6for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):7 if num == target:8 print(f"Found {target} at index {i}")All 4 passes — pass 1 is the card above pass inumtarget1 0 10 — 2 1 25 — 3 2 30 — 4 3 42 42 if num == target:
6for i, num in enumerate(numbers):7 if num42 == target42:8 print(f"Found {target42} at index {i3}")9 break10else: #?for_elseoutputFound 42 at index 3found ← False
13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):output --- Without for-else ---for i, num in enumerate(numbers):
pass 1 of 415found = False16for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):17 if num == target:18 print(f"Found {target} at index {i}")All 4 passes — pass 1 is the card above pass inumtargetfound1 0 10 — — 2 1 25 — — 3 2 30 — — 4 3 42 42 True found ← True
16for i, num in enumerate(numbers):17 if num42 == target42:18 print(f"Found {target42} at index {i3}")19 found→ True = True20 break21if not found:outputFound 42 at index 3users ← [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]
24# Practical: search with validation25print("\n--- Practical example ---")26users→ [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}] = [27 {"id": 1, "name": "Alice", "active": True},28 {"id": 2, "name": "Bob", "active": False},29 {"id": 3, "name": "Charlie", "active": True},30]31search_id→ 2 = 2 #@search_id=1, 99output --- Practical example ---for user in users:
pass 1 of 233for user{'id': 1, 'name': 'Alice', 'active': True} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")for user in users:
pass 2 of 233for user{'id': 2, 'name': 'Bob', 'active': False} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")if user["id"] == search_id:
33for user in users:34 if user["id"]2 == search_id2:35 print(f"Found user: {user['name']Bob}")36 break37else:outputFound user: Bob
numbers ← [10, 25, 30, 42, 55, 60], target ← 30
1# Python's unique for-else construct2numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]3target→ 30 = 30for i, num in enumerate(numbers):
pass 1 of 35# for-else: else runs only if loop completes WITHOUT break6for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):7 if num == target:8 print(f"Found {target} at index {i}")All 3 passes — pass 1 is the card above pass inumtarget1 0 10 — 2 1 25 — 3 2 30 30 if num == target:
6for i, num in enumerate(numbers):7 if num30 == target30:8 print(f"Found {target30} at index {i2}")9 break10else:outputFound 30 at index 2found ← False
13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):output --- Without for-else ---for i, num in enumerate(numbers):
pass 1 of 315found = False16for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):17 if num == target:18 print(f"Found {target} at index {i}")All 3 passes — pass 1 is the card above pass inumtargetfound1 0 10 — — 2 1 25 — — 3 2 30 30 True found ← True
16for i, num in enumerate(numbers):17 if num30 == target30:18 print(f"Found {target30} at index {i2}")19 found→ True = True20 break21if not found:outputFound 30 at index 2users ← [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]
24# Practical: search with validation25print("\n--- Practical example ---")26users→ [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}] = [27 {"id": 1, "name": "Alice", "active": True},28 {"id": 2, "name": "Bob", "active": False},29 {"id": 3, "name": "Charlie", "active": True},30]31search_id→ 2 = 2output --- Practical example ---for user in users:
pass 1 of 233for user{'id': 1, 'name': 'Alice', 'active': True} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")for user in users:
pass 2 of 233for user{'id': 2, 'name': 'Bob', 'active': False} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")if user["id"] == search_id:
33for user in users:34 if user["id"]2 == search_id2:35 print(f"Found user: {user['name']Bob}")36 break37else:outputFound user: Bob
numbers ← [10, 25, 30, 42, 55, 60], target ← 99
1# Python's unique for-else construct2numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]3target→ 99 = 99for i, num in enumerate(numbers):
pass 1 of 65# for-else: else runs only if loop completes WITHOUT break6for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):7 if num == target:8 print(f"Found {target} at index {i}")All 6 passes — pass 1 is the card above pass inumtarget1 0 10 — 2 1 25 — 3 2 30 — 4 3 42 — 5 4 55 — 6 5 60 99 else:
8 print(f"Found {target} at index {i}")9 break10else:11 print(f"{target99} not found")output99 not foundfound ← False
13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):output --- Without for-else ---for i, num in enumerate(numbers):
pass 1 of 615found = False16for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):17 if num == target:18 print(f"Found {target} at index {i}")All 6 passes — pass 1 is the card above pass inumfoundtarget1 0 10 — — 2 1 25 — — 3 2 30 — — 4 3 42 — — 5 4 55 — — 6 5 60 False 99 if not found:
20 break21if not foundFalse:22 print(f"{target99} not found")output99 not foundusers ← [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]
24# Practical: search with validation25print("\n--- Practical example ---")26users→ [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}] = [27 {"id": 1, "name": "Alice", "active": True},28 {"id": 2, "name": "Bob", "active": False},29 {"id": 3, "name": "Charlie", "active": True},30]31search_id→ 2 = 2output --- Practical example ---for user in users:
pass 1 of 233for user{'id': 1, 'name': 'Alice', 'active': True} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")for user in users:
pass 2 of 233for user{'id': 2, 'name': 'Bob', 'active': False} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")if user["id"] == search_id:
33for user in users:34 if user["id"]2 == search_id2:35 print(f"Found user: {user['name']Bob}")36 break37else:outputFound user: Bob
numbers ← [10, 25, 30, 42, 55, 60], target ← 42
1# Python's unique for-else construct2numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]3target→ 42 = 42for i, num in enumerate(numbers):
pass 1 of 45# for-else: else runs only if loop completes WITHOUT break6for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):7 if num == target:8 print(f"Found {target} at index {i}")All 4 passes — pass 1 is the card above pass inumtarget1 0 10 — 2 1 25 — 3 2 30 — 4 3 42 42 if num == target:
6for i, num in enumerate(numbers):7 if num42 == target42:8 print(f"Found {target42} at index {i3}")9 break10else:outputFound 42 at index 3found ← False
13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):output --- Without for-else ---for i, num in enumerate(numbers):
pass 1 of 415found = False16for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):17 if num == target:18 print(f"Found {target} at index {i}")All 4 passes — pass 1 is the card above pass inumtargetfound1 0 10 — — 2 1 25 — — 3 2 30 — — 4 3 42 42 True found ← True
16for i, num in enumerate(numbers):17 if num42 == target42:18 print(f"Found {target42} at index {i3}")19 found→ True = True20 break21if not found:outputFound 42 at index 3users ← [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]
24# Practical: search with validation25print("\n--- Practical example ---")26users→ [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}] = [27 {"id": 1, "name": "Alice", "active": True},28 {"id": 2, "name": "Bob", "active": False},29 {"id": 3, "name": "Charlie", "active": True},30]31search_id→ 1 = 1output --- Practical example ---for user in users:
33for user{'id': 1, 'name': 'Alice', 'active': True} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")if user["id"] == search_id:
33for user in users:34 if user["id"]1 == search_id1:35 print(f"Found user: {user['name']Alice}")36 break37else:outputFound user: Alice
numbers ← [10, 25, 30, 42, 55, 60], target ← 42
1# Python's unique for-else construct2numbers→ [10, 25, 30, 42, 55, 60] = [10, 25, 30, 42, 55, 60]3target→ 42 = 42for i, num in enumerate(numbers):
pass 1 of 45# for-else: else runs only if loop completes WITHOUT break6for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):7 if num == target:8 print(f"Found {target} at index {i}")All 4 passes — pass 1 is the card above pass inumtarget1 0 10 — 2 1 25 — 3 2 30 — 4 3 42 42 if num == target:
6for i, num in enumerate(numbers):7 if num42 == target42:8 print(f"Found {target42} at index {i3}")9 break10else:outputFound 42 at index 3found ← False
13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):output --- Without for-else ---for i, num in enumerate(numbers):
pass 1 of 415found = False16for i0, num10 in enumerate(numbers[10, 25, 30, 42, 55, 60]):17 if num == target:18 print(f"Found {target} at index {i}")All 4 passes — pass 1 is the card above pass inumtargetfound1 0 10 — — 2 1 25 — — 3 2 30 — — 4 3 42 42 True found ← True
16for i, num in enumerate(numbers):17 if num42 == target42:18 print(f"Found {target42} at index {i3}")19 found→ True = True20 break21if not found:outputFound 42 at index 3users ← [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]
24# Practical: search with validation25print("\n--- Practical example ---")26users→ [{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}] = [27 {"id": 1, "name": "Alice", "active": True},28 {"id": 2, "name": "Bob", "active": False},29 {"id": 3, "name": "Charlie", "active": True},30]31search_id→ 99 = 99output --- Practical example ---for user in users:
pass 1 of 333for user{'id': 1, 'name': 'Alice', 'active': True} in users[{'id': 1, 'name': 'Alice', 'active': True}, {'id': 2, 'name': 'Bob', 'active': False}, {'id': 3, 'name': 'Charlie', 'active': True}]:34 if user["id"] == search_id:35 print(f"Found user: {user['name']}")All 3 passes — pass 1 is the card above pass usersearch_id1 {'id': 1, 'name': 'Alice', 'active': True} — 2 {'id': 2, 'name': 'Bob', 'active': False} — 3 {'id': 3, 'name': 'Charlie', 'active': True} 99 else:
35 print(f"Found user: {user['name']}")36 break37else:38 print(f"User {search_id99} not found")outputUser 99 not found
for-else is a Pythonic way to handle "not found" scenarios.
Exercise: refactoring.py
Explore Pythonic alternatives to break/continue