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.

target
break.py
Replay: real traced execution (multi-file project)
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

  1. 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):
  2. for i, num in enumerate(numbers):

    pass 1 of 4
    4found_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: 10
    All 4 passes — pass 1 is the card above
    passinumtargetfound_index
    1010
    2125
    3230
    4342423
  3. found_index ← 3

    6print(f"Checking index {i}: {num}")7if num42 == target42:8    found_index→ 3 = i39    break  #?break_exit
  4. if found_index != -1:

    11if found_index3 != -1:12    print(f"Found {target42} at index {found_index3}")13else:
    outputFound 42 at index 3
  1. 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):
  2. for i, num in enumerate(numbers):

    pass 1 of 3
    4found_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: 10
    All 3 passes — pass 1 is the card above
    passinumtargetfound_index
    1010
    2125
    3230302
  3. found_index ← 2

    6print(f"Checking index {i}: {num}")7if num30 == target30:8    found_index→ 2 = i29    break
  4. if found_index != -1:

    11if found_index2 != -1:12    print(f"Found {target30} at index {found_index2}")13else:
    outputFound 30 at index 2
  1. 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):
  2. for i, num in enumerate(numbers):

    pass 1 of 6
    4found_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: 10
    All 6 passes — pass 1 is the card above
    passinumtarget
    1010
    2125
    3230
    4342
    5455
    656099
  3. 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.

break Exit the innermost loop immediately. Loop terminates.

Skip invalid entries (continue)

Skip items that don't meet criteria without stopping the loop.

continue.py
Replay: real traced execution (multi-file project)
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)}")

  1. 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:
  2. total ← 85, count ← 1

    pass 1 of 7
    6print("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 += 1
    output  Adding: 85
    All 7 passes — pass 1 is the card above
    passscoretotalcount
    1850 850 1
    2-1
    39285 1771 2
    401772 3
    578177 2553 4
    6-5
    795255 3504 5
  3. if score < 0: #?skip_invalid

    pass 1 of 2
    7for 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: -1
  4. if score < 0: #?skip_invalid

    pass 2 of 2
    7for 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: -5
  5. print(f"Valid scores: {count}")

    15print(f"Valid scores: {count5}")16print(f"Sum: {total350}")17if count > 0:
    outputValid scores: 5
    Sum: 350
  6. if count > 0:

    16print(f"Sum: {total}")17if count5 > 0:18    print(f"Average: {total350 // count5}")
    outputAverage: 70
  7. valid_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.

continue Skip rest of current iteration, go to next iteration.

Early exit on error

Stop processing if something goes wrong.

commands
early_exit.py
Replay: real traced execution (multi-file project)
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.")
  1. 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 = True
  2. for cmd in commands:

    pass 1 of 3
    6for 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
    passcmdsuccess
    1load
    2process
    3errorFalse
  3. success ← False

    9# Stop on error10if cmderror == "error":11    print("ERROR: Operation failed!")12    success→ False = False13    break
    outputERROR: Operation failed!
  4. else:

    17if success:18    print("All commands completed successfully.")19else:20    print("Processing stopped due to error.")
    outputProcessing stopped due to error.
  1. commands ← ['init', 'run', 'complete'], success ← True

    1commands→ ['init', 'run', 'complete'] = ["init", "run", "complete"]23success→ True = True
  2. for cmd in commands:

    pass 1 of 3
    5for 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
    passcmdsuccess
    1init
    2run
    3completeTrue
  3. if success:

    16if successTrue:17    print("All commands completed successfully.")18else:
    outputAll commands completed successfully.
  1. commands ← ['start', 'stop'], success ← True

    1commands→ ['start', 'stop'] = ["start", "stop"]23success→ True = True
  2. for cmd in commands:

    pass 1 of 2
    5for 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.
  3. for cmd in commands:

    pass 2 of 2
    5for 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.
  4. 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
sentinel.py
Replay: real traced execution (multi-file project)
# 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}")

  1. 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 = 0
    outputProcessing until sentinel (-1):
  2. total ← 10

    pass 1 of 5
    8for 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 += value10
    outputProcessing: 10
    All 5 passes — pass 1 is the card above
    passvaluetotal
    1100 10
    22010 30
    33030 60
    44060 100
    5-1
  3. 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.
  4. 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:
  5. for value in takewhile(lambda x: x != -1, data2):

    pass 1 of 4
    21data2 = [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: 10
    All 4 passes — pass 1 is the card above
    passvalue
    110
    220
    330
    440
  6. total2 ← 100

    25total2→ 100 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]))26print(f"Sum: {total2100}")
    outputSum: 100
  1. 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 = 0
    outputProcessing until sentinel (-1):
  2. total ← 5

    pass 1 of 4
    7for 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 += value5
    outputProcessing: 5
    All 4 passes — pass 1 is the card above
    passvaluetotal
    150 5
    2105 15
    31515 30
    4-1
  3. 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.
  4. 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:
  5. for value in takewhile(lambda x: x != -1, data2):

    pass 1 of 4
    20data2 = [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: 10
    All 4 passes — pass 1 is the card above
    passvalue
    110
    220
    330
    440
  6. total2 ← 100

    24total2→ 100 = sum(takewhile(lambda x: x != -1, data2[10, 20, 30, 40, -1, 50, 60]))25print(f"Sum: {total2100}")
    outputSum: 100
  1. 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 = 0
    outputProcessing until sentinel (-1):
  2. total ← 100

    pass 1 of 4
    7for 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 += value100
    outputProcessing: 100
    All 4 passes — pass 1 is the card above
    passvaluetotal
    11000 100
    2200100 300
    3300300 600
    4400600 1000
  3. 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:
  4. for value in takewhile(lambda x: x != -1, data2):

    pass 1 of 4
    20data2 = [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: 10
    All 4 passes — pass 1 is the card above
    passvalue
    110
    220
    330
    440
  5. 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.

sentinel Special value marking end of data: -1, None, "END", etc.

For-else (Python unique!)

Python's for-else executes else only if loop completes without break.

example
for_else.py
Replay: real traced execution (multi-file project)
# 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")

  1. 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, 99
  2. for i, num in enumerate(numbers):

    pass 1 of 4
    5# 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
    passinumtarget
    1010
    2125
    3230
    434242
  3. if num == target:

    6for i, num in enumerate(numbers):7    if num42 == target42:8        print(f"Found {target42} at index {i3}")9        break10else:  #?for_else
    outputFound 42 at index 3
  4. found ← False

    13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):
    output
    --- Without for-else ---
  5. for i, num in enumerate(numbers):

    pass 1 of 4
    15found = 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
    passinumtargetfound
    1010
    2125
    3230
    434242True
  6. 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 3
  7. users ← [{'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, 99
    output
    --- Practical example ---
  8. for user in users:

    pass 1 of 2
    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']}")
  9. for user in users:

    pass 2 of 2
    33for 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']}")
  10. 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
  1. 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 = 30
  2. for i, num in enumerate(numbers):

    pass 1 of 3
    5# 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
    passinumtarget
    1010
    2125
    323030
  3. 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 2
  4. found ← False

    13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):
    output
    --- Without for-else ---
  5. for i, num in enumerate(numbers):

    pass 1 of 3
    15found = 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
    passinumtargetfound
    1010
    2125
    323030True
  6. 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 2
  7. users ← [{'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
    output
    --- Practical example ---
  8. for user in users:

    pass 1 of 2
    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']}")
  9. for user in users:

    pass 2 of 2
    33for 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']}")
  10. 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
  1. 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 = 99
  2. for i, num in enumerate(numbers):

    pass 1 of 6
    5# 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
    passinumtarget
    1010
    2125
    3230
    4342
    5455
    656099
  3. else:

    8        print(f"Found {target} at index {i}")9        break10else:11    print(f"{target99} not found")
    output99 not found
  4. found ← False

    13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):
    output
    --- Without for-else ---
  5. for i, num in enumerate(numbers):

    pass 1 of 6
    15found = 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
    passinumfoundtarget
    1010
    2125
    3230
    4342
    5455
    6560False99
  6. if not found:

    20        break21if not foundFalse:22    print(f"{target99} not found")
    output99 not found
  7. users ← [{'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
    output
    --- Practical example ---
  8. for user in users:

    pass 1 of 2
    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']}")
  9. for user in users:

    pass 2 of 2
    33for 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']}")
  10. 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
  1. 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
  2. for i, num in enumerate(numbers):

    pass 1 of 4
    5# 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
    passinumtarget
    1010
    2125
    3230
    434242
  3. 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 3
  4. found ← False

    13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):
    output
    --- Without for-else ---
  5. for i, num in enumerate(numbers):

    pass 1 of 4
    15found = 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
    passinumtargetfound
    1010
    2125
    3230
    434242True
  6. 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 3
  7. users ← [{'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 = 1
    output
    --- Practical example ---
  8. 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']}")
  9. 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
  1. 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
  2. for i, num in enumerate(numbers):

    pass 1 of 4
    5# 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
    passinumtarget
    1010
    2125
    3230
    434242
  3. 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 3
  4. found ← False

    13# Equivalent without for-else14print("\n--- Without for-else ---")15found→ False = False16for i, num in enumerate(numbers):
    output
    --- Without for-else ---
  5. for i, num in enumerate(numbers):

    pass 1 of 4
    15found = 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
    passinumtargetfound
    1010
    2125
    3230
    434242True
  6. 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 3
  7. users ← [{'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 = 99
    output
    --- Practical example ---
  8. for user in users:

    pass 1 of 3
    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']}")
    All 3 passes — pass 1 is the card above
    passusersearch_id
    1{'id': 1, 'name': 'Alice', 'active': True}
    2{'id': 2, 'name': 'Bob', 'active': False}
    3{'id': 3, 'name': 'Charlie', 'active': True}99
  9. 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.

for-else The `else` block runs only if the loop wasn't broken out of.

Exercise: refactoring.py

Explore Pythonic alternatives to break/continue