Module 15: Advanced Loop Control

Applying `break` and `continue` in more complex scenarios.

Nested Loops & Control

Predict the output of this nested loop. Note how `break` only exits the *inner* loop.

count = 0
for i in range(3): # Outer loop: 0, 1, 2
    for j in range(4): # Inner loop: 0, 1, 2, 3
        if j == 2:
            break # Exit inner loop
        count += 1
print(count)

The `for...else` Construct

Python loops have an optional `else` block that runs only if the loop completes *without* encountering a `break`. Predict if the `else` block runs in this code.

found_target = False
target = 5
numbers = [1, 8, 3, 4, 9]
for num in numbers:
    print(f"Checking {num}")
    if num == target:
        print("Target found!")
        found_target = True
        break
else:
    print("Target not found in the list.")
Explanation: The `else` block associated with a `for` or `while` loop executes only when the loop terminates normally (i.e., finishes iterating through all items or the `while` condition becomes false), *not* when the loop is exited prematurely by a `break` statement.

Debug the Loop

This code intends to print numbers from 0 to 4, skipping 2. However, there's a logic error involving `continue`. What will this code *actually* print?

for i in range(5):
    print(i) # Print happens BEFORE the check!
    if i == 2:
        continue # Skips...? (Too late!)
    # Some other code might be here in a real scenario

Select the actual output:

Advanced Mission: Data Filtering

Process a list of sensor readings (numbers). Skip any reading below 0 using `continue`. If a reading is exactly 100, print "Threshold reached!" and stop processing immediately using `break`. Print all valid readings processed *before* hitting the threshold.

Filter Sensor Data

sensor_data = [15, 22, -5, 30, 99, 100, 45, -10]

Write the Python loop below to filter `sensor_data` as described.

Advanced Practice Complete!

Fantastic! You've tackled more complex loop control scenarios using `break`, `continue`, and `for...else`.
Feel free to revisit the Standard Practice, watch the Video Lesson, or return to the Course Menu.