Module 15: Loop Control Practice

Mastering `break` and `continue` for precise loop management.

Anatomy of Loop Control

Loops sometimes need finer control. Click on the highlighted keywords (`for`, `if`, `break`, `continue`) to understand their roles in this example.

for num in range(1, 6):
    if num == 3:
        continue # Skip number 3
    if num == 5:
        break # Stop when 5 is reached
    print(num)

Identify all 4 parts!

Predict the Output

Examine the code below. What numbers will it actually print? Click the button with the correct output sequence.

for i in range(1, 8): # Numbers 1 through 7
    if i % 2 == 0: # If i is even
        continue # Skip even numbers
    if i == 5:
        break # Stop if i is 5
    print(i)

Build-a-Loop Challenge

Drag the pieces to build a loop that prints numbers from 0 up to (but not including) 4, but stops immediately if the number is 2. Use `break`. Arrange them correctly, including indentation!

Drop pieces here to build the loop...

Your Turn: Use `continue`

Write Python code in the editor below. Use a `for` loop to iterate from 0 to 5 (inclusive). Inside the loop, use `continue` to skip printing the number 3. Print all other numbers.

Output will appear here...

Loop Control Missions!

Apply your `break` and `continue` skills to solve these challenges. Check your code using the "Test Mission" buttons.

Mission 1: Find First Multiple of 7

Write a loop that iterates through numbers 1 to 20. Find the first number divisible by 7 (using the modulo operator `%`). Print only that number and then immediately stop the loop using `break`.

Mission 2: Skip Vowels

Iterate through the string "programming". Print each character, but use `continue` to skip printing any vowels (a, e, i, o, u). Print consonants on separate lines.

Mission 3: `while` Loop Escape

Create a `while True` loop. Inside, print the message "Looping..." and then immediately use `break` to exit after the first print. (This demonstrates controlling infinite loops).

Module 15 Practice Complete!

Excellent work! You've practiced controlling loops with `break` and `continue`. This gives you much finer control over your iterations.
Ready for more? Tackle the Advanced Practice for Module 15 or proceed to the next module!