Python Loop Controls (break, continue, else)
The break statement immediately terminates the loop as soon as a target condition is met, transferring execution to the first line following the loop:
# 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. โ
")
- Prints
Processing number: 1, thenProcessing number: 2. - When
i == 3,breakterminates the loop. Numbers 4 and 5 are never processed!
The continue statement skips the remainder of the current iteration and jumps directly to the next loop cycle:
# 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! โ
")
breakdestroys and terminates the entire loop.continueskips only the current cycle and keeps the loop running for subsequent elements.
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:
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.")
Because num == 30 matched, break executed, cleanly bypassing the else: block.
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!
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)")
Think of loop else as "if nobreak:". It runs only when the loop completes all iterations naturally.
Checking if a number is prime using the loop else search pattern:
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)")
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!
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.
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".
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.")
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.