Neural Sync Active
Loop Control: break, continue, pass
Registry Synced
Loop Control: break, continue, pass
1530 words
8 min read
Reading compass
Now ยท ๐ฏ Learning Objectives
Loop Control: break, continue, pass
Why read this? Sometimes you need to exit a loop early (found what you needed), skip an iteration (invalid data), or do nothing at all (placeholder). Python gives youbreak,continue, andpassfor exactly these situations.
๐ฏ Learning Objectives
By the end of this topic, you will be able to:
- Exit loops early with
break - Skip to the next iteration with
continue - Use
passas a placeholder for empty code blocks - Use the
elseclause with loops (triggered on normal completion) - Write robust input validation loops
๐ Prerequisites
- While Loops and For Loops
- Understanding of loop mechanics.
๐ Core Content
12.1 The break Statement โ Exiting Early
What problem does this solve? When you're searching for something, you want to stop as soon as you find it โ no need to keep looking.
python# runnable numbers = [3, 7, 1, 9, 4, 2, 8] target = 9 for num in numbers: print(f"Checking {num}") if num == target: print(f"Found {target}! Stopping.") break
Output:
pseudoChecking 3 Checking 7 Checking 1 Checking 9 Found 9! Stopping.
After
break, execution continues after the loop (not after the program).12.2 The continue Statement โ Skip This Iteration
What problem does this solve? When processing data, you sometimes need to skip certain items (e.g., skip empty lines, invalid entries).
python# runnable for num in range(1, 11): if num % 3 == 0: continue # skip multiples of 3 print(num, end=" ")
Output:
pseudo1 2 4 5 7 8 10
Flow:
(Diagram)
12.3 The pass Statement โ Do Nothing
What problem does this solve? Python requires indented code after
if, for, while, etc. If you're sketching out structure but haven't written the code yet, pass fills the requirement.python# runnable for i in range(5): pass # TODO: implement later if True: pass # placeholder def not_implemented_yet(): pass # allows empty function body
Without
pass, an empty block causes IndentationError or SyntaxError.12.4 Loop else โ "No Break Occurred"
The
else clause on loops runs if the loop completed normally (not via break).python# runnable # Search for a prime factor n = 17 for i in range(2, int(n**0.5) + 1): if n % i == 0: print(f"{n} is divisible by {i}") break else: print(f"{n} is prime!") # runs because no break
Output:
17 is prime!12.5 Worked Example 1: Input Validation with while-break
python# runnable while True: age = input("Enter your age (or 'quit' to exit): ") if age.lower() == 'quit': print("Goodbye!") break try: age = int(age) if 0 <= age <= 150: print(f"You are {age} years old.") break else: print("Age must be 0-150.") except ValueError: print("Invalid input. Enter a number or 'quit'.")
12.6 Worked Example 2: Processing Data with continue
python# runnable data = ["apple", "", "banana", None, "cherry", "", "date"] for item in data: if not item: # skip None, empty strings continue print(f"Processing: {item}")
Output:
pseudoProcessing: apple Processing: banana Processing: cherry Processing: date
12.7 Worked Example 3: Early Exit in Search
python# runnable def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False # like break + return return True # Find first 10 primes count = 0 num = 2 while count < 10: if is_prime(num): print(num, end=" ") count += 1 num += 1
12.8 Worked Example 4: Nested Loop Break
python# runnable # Find first pair whose product > 50 for a in range(1, 11): for b in range(1, 11): if a * b > 50: print(f"Found: {a} ร {b} = {a*b}") break # breaks inner loop only else: continue # if inner didn't break, continue outer break # if inner broke, break outer too
Output:
pseudoFound: 6 ร 9 = 54
12.9 Worked Example 5: Menu System
python# runnable while True: print("\n--- MENU ---") print("1. Say Hello") print("2. Show date") print("3. Exit") choice = input("Choose (1-3): ") if choice == '1': print("Hello!") continue # go back to menu elif choice == '2': import datetime print(f"Today: {datetime.date.today()}") continue elif choice == '3': print("Goodbye!") break else: print("Invalid choice, try again.")
๐ Key Concepts Reference
| Statement | Effect | When to Use |
|---|---|---|
break | Exit the loop immediately | Found what you need, stop searching |
continue | Skip rest of body, next iteration | Skip invalid/unwanted items |
pass | Do nothing (placeholder) | Need an empty block syntactically |
Loop else | Run if loop completes without break | Confirm "not found" after search |
โ ๏ธ Common Pitfalls
Pitfall 1: break Only Breaks the Innermost Loop
The mistake: Using
break in a nested loop expecting it to break all loops. Fix: Use a flag variable, or for-else-continue-break pattern (see example 4).Pitfall 2: continue in While Loop Forgets Update
The mistake:
continue skips the increment, causing infinite loop.pythoni = 0 while i < 10: if i % 2 == 0: continue # skips i += 1! i += 1
Fix: Put the update BEFORE the
continue, or use a for loop.Pitfall 3: Confusing pass with continue
The mistake: Using
pass to skip an iteration โ pass does nothing but still continues normally. Fix: Use continue to skip to the next iteration of a loop. Use pass only for empty blocks.๐ Practice Questions
Q1: What does this output?pythonfor i in range(5): if i == 3: break print(i)Answer:pseudo0 1 2When i=3, break exits the loop. So 3 and 4 are never printed. Q2: What does this output?pythonfor i in range(5): if i == 3: continue print(i)Answer:pseudo0 1 2 4continueskips printing for i=3, but loop continues with i=4. Q3: What's the difference between pass and continue?Answer:
passdoes nothing. Execution continues to the next line. Used for empty blocks.continueskips the rest of the current iteration and goes to the next loop iteration. Used only inside loops. Q4: When does the else clause of a loop run?Answer: Theelseruns when the loop condition becomes False (forwhile) or when the sequence is exhausted (forfor), AND nobreakstatement was executed. Q5: Write a loop that finds and prints the first number divisible by 7 between 1 and 100.Answer:python# runnable for i in range(1, 101): if i % 7 == 0: print(f"First number divisible by 7: {i}") breakQ6: What's wrong with this code?pythoni = 0 while i < 5: if i == 2: continue print(i) i += 1Answer: Infinite loop! When i=2,continueskipsi += 1, so i stays 2 forever. Fix: increment before the continue, or use a for loop. Q7: Write code that prints all numbers 1-20 EXCEPT multiples of 3 (use continue).Answer:python# runnable for i in range(1, 21): if i % 3 == 0: continue print(i, end=" ")Output:1 2 4 5 7 8 10 11 13 14 16 17 19 20Q8: What does this output?pythonfor i in range(3): for j in range(3): if j == 1: break print(f"({i},{j})", end=" ") print()Answer:pseudo(0,0) (1,0) (2,0)The innerbreakexits the inner loop when j=1, so only j=0 is printed for each i. Q9: Write a while loop that keeps asking for input until "yes" or "no" is entered.Answer:python# runnable while True: answer = input("Enter yes or no: ").lower() if answer in ("yes", "no"): print(f"You entered: {answer}") break print("Invalid, try again.")Q10: Write a program that prints all prime numbers up to 50 using a loop withelse.Answer:python# runnable for n in range(2, 51): for i in range(2, int(n**0.5) + 1): if n % i == 0: break else: print(n, end=" ")Output:2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
๐ Cross-References
- Next Topic: Pattern Printing & Formatted Output
- Previous Topic: Nested Loops & Loop Patterns
- Reference: Python for Everybody, Chapter 5 (Section 5.4)
- Video: L41: Break continue & pass in python explained with examples Join Discord Previous11. Nested LoopsNext13. Pattern Printing