break, continue & Loop-Else
Sometimes you need to bail out of a loop early, or skip certain iterations. Python gives you three precise tools for fine-grained loop control.
break to exit a loop earlycontinue to skip iterationsfor...else patternThree Loop Control Tools
π break
Immediately exits the entire loop. Code after the loop runs next.
for i in range(10):
if i == 5:
break
# jumps hereβοΈ continue
Skips the rest of this iteration. Jumps back to the loop condition.
for i in range(5):
if i == 2:
continue
print(i)
# 0,1,3,4π for...else
The else block runs only if the loop finished without hitting break.
for i in data:
if found:
break
else:
print("not found")break β The Emergency Exit
break is perfect when you're searching for something and want to stop as soon as you find it:
continue β Skip and Move On
continue skips the rest of the current iteration and jumps to the next one:
for...else β "Did We Find It?"
Python's unique for...else pattern: the else block runs only if the loop completed without break. Perfect for search-and-report:
Challenges
Challenge 1: First Vowel Finder
Find the first vowel in a word using break.
Hint: Use
for char in word: to iterate through characters.for char in word: gives you each letter.Hint 2:
if char.lower() in "aeiou": checks if it's a vowel.Hint 3: Inside the if:
first_vowel = char then breakChallenge 2: Positive Sum
Sum only the positive numbers from a list, using continue to skip negatives.
for n in numbers:Hint 2:
if n < 0: continue β skips to the next iterationHint 3: After the continue check:
total += nChallenge 3: Password Attempts
Simulate a login system with limited attempts using a loop with break.
Try using for...else for this!
for guess in attempts: β try each oneHint 2:
if guess == secret: result = "Access granted" then breakHint 3: Use for...else: the
else: block sets result = "Account locked" β it only runs if no break happened.Challenge 4: Prime Finder
Find all prime numbers up to limit using nested loops with for...else.
Example: limit=20 β "2 3 5 7 11 13 17 19"
for num in range(2, limit + 1):Hint 2: Inner:
for i in range(2, num): β if num % i == 0: breakHint 3: Add
else: after the inner loop (aligned with inner for): primes += str(num) + " "