Python Loop Controls (break, continue, else)

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 9 of 65 ๐Ÿ“‚ Phase 2: Operators & Control Flow ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: break ยท continue ยท pass ยท Loop else Clause ยท Prime Checker
Master loop controls: early exit with break, skipping iterations with continue, pass stubs, and the Python loop else clause.
1The break Statement (Early Loop Exit)

The break statement immediately terminates the loop as soon as a target condition is met, transferring execution to the first line following the loop:

๐Ÿ’ป Example 1: Terminating Loop Early with break
# Search for target number 3 and stop immediately:
print("Starting loop:")

for i in range(1, 6):
    if i == 3:
        print("๐ŸŽฏ Target number 3 found! Stopping loop immediately.")
        break  # Loop exits right here!
        
    print("Processing number:", i)

print("Program continued after break. โœ…")
๐Ÿ” Execution Flow:
  • Prints Processing number: 1, then Processing number: 2.
  • When i == 3, break terminates the loop. Numbers 4 and 5 are never processed!
2The continue Statement (Skipping Iterations)

The continue statement skips the remainder of the current iteration and jumps directly to the next loop cycle:

๐Ÿ’ป Example 2: Skipping Current Iteration with continue
# Skip number 3 and continue with the rest of the numbers:
print("Starting loop with continue:")

for i in range(1, 6):
    if i == 3:
        print("โญ๏ธ Skipping number 3...")
        continue  # Skips remaining lines in this iteration only!
        
    print("Processing number:", i)

print("Loop finished! โœ…")
๐Ÿ” Difference between break and continue:
  • break destroys and terminates the entire loop.
  • continue skips only the current cycle and keeps the loop running for subsequent elements.
3The Python Loop else Clause (Item Found Case)

In Python, you can attach an else block directly to a for or while loop. The loop else block executes ONLY if the loop finishes without hitting a break statement. If break occurs, the else is skipped:

๐Ÿ’ป Example 3: Loop else Clause when Target is Found (break triggered)
numbers = [10, 20, 30, 40]
target = 30

for num in numbers:
    if num == target:
        print(f"โœ… Target {target} found in list!")
        break  # break triggers -> loop else is BYPASSED!
else:
    print(f"โŒ Target {target} not found.")
๐Ÿ” Why else was bypassed:

Because num == 30 matched, break executed, cleanly bypassing the else: block.

4The Python Loop else Clause (Item NOT Found Case)

When the target is not in the list, the loop runs to natural completion without hitting break, so the else executes automatically โ€” eliminating the need for boolean flags!

๐Ÿ’ป Example 4: Loop else Clause when Target is Missing
numbers = [10, 20, 30, 40]
target = 99  # Number is not in the list

for num in numbers:
    if num == target:
        print(f"โœ… Target {target} found!")
        break
else:
    # Executes automatically because no break occurred!
    print(f"โŒ Target {target} was NOT found in the list! (Handled by loop else)")
๐Ÿ” The Golden Rule of Loop else:

Think of loop else as "if nobreak:". It runs only when the loop completes all iterations naturally.

5Real-World Application: Prime Number Checker with Loop else

Checking if a number is prime using the loop else search pattern:

๐Ÿ’ป Example 5: Prime Number Verification using Loop else
num = 17

# Check for divisors from 2 up to num - 1:
for i in range(2, num):
    if num % i == 0:
        print(f"{num} is NOT prime (divisible by {i})")
        break
else:
    # Executes if no number divided 'num' evenly:
    print(f"๐ŸŒŸ {num} is a PRIME NUMBER! (No divisors found)")
๐Ÿ” How it works:

If any number from 2 to 16 divides 17, break triggers. Since no number divides 17, the loop finishes all iterations and the else: block prints that 17 is Prime!

โš ๏ธ Common Developer Pitfall: Expecting loop else to Execute After a break

Remember: If a loop exits via a break statement, the loop else block is completely bypassed. It only runs if the loop exhausts all items naturally or condition becomes false.

๐Ÿ’ป Hands-on Interactive Practice Challenge

Search for student "Balaji" in a list of names. If found, print a greeting and break; if not found, let loop else print "Student not in class".

Python 3 Practice Challenge โ–ถ Run in Compiler
students = ["Alex", "Balaji", "Chloe", "David"]
search_name = "Balaji"

for name in students:
    if name == search_name:
        print(f"๐Ÿ‘‹ Found {search_name}! Welcome to class.")
        break
else:
    print(f"โŒ {search_name} is not enrolled in this class.")
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

Q Why did Guido van Rossum choose the keyword "else" for loops?

Guido wanted a keyword that signifies "if no break occurred". While some developers suggest "nobreak" would be clearer, "else" was chosen to keep Python's keyword count minimal.

Q Does while-else work the same way as for-else?

Yes. In a while-else loop, the else block runs when the while condition evaluates to False. If the while loop exits via break, the else block is skipped.

Q How can I break out of nested loops simultaneously?

In Python, the cleanest ways to exit nested loops are: (1) wrap the nested loops inside a function and use "return", (2) set a boolean flag, or (3) raise a custom exception.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026