Quiz 2

Loop Control: break, continue, pass

1530 words
8 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# 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 you `break`, `continue`, and `pass` for exactly these situations.

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 you break, continue, and pass for exactly these situations.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Exit loops early with break
  2. Skip to the next iteration with continue
  3. Use pass as a placeholder for empty code blocks
  4. Use the else clause with loops (triggered on normal completion)
  5. Write robust input validation loops

📋 Prerequisites


📖 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:
pseudo
Checking 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:
pseudo
1 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:
pseudo
Processing: apple
Processing: banana
Processing: cherry
Processing: date
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:
pseudo
Found: 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

StatementEffectWhen to Use
breakExit the loop immediatelyFound what you need, stop searching
continueSkip rest of body, next iterationSkip invalid/unwanted items
passDo nothing (placeholder)Need an empty block syntactically
Loop elseRun if loop completes without breakConfirm "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.
python
i = 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?
python
for i in range(5):
    if i == 3:
        break
    print(i)
Answer:
pseudo
0
1
2
When i=3, break exits the loop. So 3 and 4 are never printed. Q2: What does this output?
python
for i in range(5):
    if i == 3:
        continue
    print(i)
Answer:
pseudo
0
1
2
4
continue skips printing for i=3, but loop continues with i=4. Q3: What's the difference between pass and continue?
Answer:
  • pass does nothing. Execution continues to the next line. Used for empty blocks.
  • continue skips 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: The else runs when the loop condition becomes False (for while) or when the sequence is exhausted (for for), AND no break statement 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}")
        break
Q6: What's wrong with this code?
python
i = 0
while i < 5:
    if i == 2:
        continue
    print(i)
    i += 1
Answer: Infinite loop! When i=2, continue skips i += 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 20 Q8: What does this output?
python
for 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 inner break exits 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 with else.
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

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.