Lesson 23/48 ยท ๐Ÿ” Loops & Repetition
๐Ÿ” Loops & RepetitionLesson 23/48
Phase 3 ยท Loops & Repetition18 min

Loop Control, break, continue, pass

Take back control of your loops instead of letting them run on autopilot

Loops run until their condition is False, but sometimes you need to cut a loop short or skip an iteration. That's what break, continue, and pass are for.
break, exit the loop immediately
break stops the loop entirelypython
# Find the first negative number
numbers = [4, 7, 2, -1, 8, -3]
for n in numbers:
    if n < 0:
        print(f"Found negative: {n}")
        break   # stop, no need to check the rest
# Output: Found negative: -1
continue, skip the rest of this iteration, jump to the next
continue skips one iterationpython
# Print only odd numbers
for i in range(1, 8):
    if i % 2 == 0:
        continue    # skip even numbers
    print(i)
# Output: 1, 3, 5, 7
๐Ÿค”Quick Check

What does continue do inside a loop?

pass, do nothing (a placeholder)
Python doesn't allow empty blocks. Use pass when you need a block syntactically but don't want to do anything yet:
pass as a placeholderpython
for i in range(5):
    if i == 3:
        pass   # TODO: handle this case later
    else:
        print(i)
# Output: 0, 1, 2, 4
while with break, the "search" pattern
A common pattern: loop forever until you find what you're looking for:
break out of a while looppython
attempts = 0
secret = 42
guesses = [10, 55, 42, 7]   # simulating user guesses

for guess in guesses:
    attempts += 1
    if guess == secret:
        print(f"Found it in {attempts} attempts!")
        break
else:
    # The loop's else runs only if we never hit break
    print("Not found")
The for/else pattern is unique to Python: the else block runs only if the loop completed *without* hitting a break. Very useful for "search and report" patterns.
๐Ÿค”Quick Check

When does a for loop's else block execute?

Practice Exercises

0/3 solved
Exercise 1 of 3easy
โฑ 00:00

First Vowel Finder

Loop through the string "Python is great" and print the first vowel found, then stop.
Expected output: First vowel: y
Vowels are: a, e, i, o, u, y (for this exercise, y counts)
solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00

Skip the Negatives

Print all numbers from the list, but skip any negatives using continue.
Given: numbers = [3, -1, 7, -4, 2, -8, 5]Expected output (one per line): 3 7 2 5
solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00

Find or Report

Search the list for the number 99. If found, print "Found 99 at index X". If not found (loop ends without break), print "99 not in list".
Given: nums = [4, 17, 99, 3, 8]Expected output: Found 99 at index 2
solution.py
3 / 3
Solve all 3 exercises to unlock completion