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: -1continue, 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
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, 4while with break, the "search" pattern
A common pattern: loop forever until you find what you're looking for:
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 solvedExercise 1 of 3easy
โฑ 00:00First Vowel Finder
Loop through the string "Python is great" and print the first vowel found, then stop.
Expected output:
Vowels are: a, e, i, o, u, y (for this exercise, y counts)
Expected output:
First vowel: yVowels are: a, e, i, o, u, y (for this exercise, y counts)
solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00Skip 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):
Given: numbers = [3, -1, 7, -4, 2, -8, 5]Expected output (one per line):
3 7 2 5solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00Find 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:
Given: nums = [4, 17, 99, 3, 8]Expected output:
Found 99 at index 2solution.py
3 / 3
Solve all 3 exercises to unlock completion