Break Continue Pass In Python
Python Break and Continue: Controlling Loop Flow
In Python, break and continue statements can alter the flow of a normal loop. Use them when you need to exit a loop early or skip specific iterations based on a condition.
The break statement is used to terminate the loop entirely. It "breaks" out of the loop and moves the program execution to the next line of code after the loop block.
for
fruits = ["apple", "banana", "cherry", "orange"]
for x in fruits:
if x == "cherry":
break
print(x)
Output:
apple
banana
(The loop stops as soon as it hits "cherry")
while
i = 1
while i < 10:
print(i)
if i == 5:
break
i += 1
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. The loop does not stop; it moves on to the next item or check.
for
fruits = ["apple", "banana", "cherry", "orange"]
for x in fruits:
if x == "banana":
continue
print(x)
Output:
apple
cherry
orange
(Notice "banana" is missing from the output)
while
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
3. Comparison: Break vs. Continue
| Feature | break | continue |
| :--- | :--- | :--- |
| Effect | Stops the whole loop | Skips one iteration |
| Execution | Jumps to code after the loop | Jumps to the next iteration |
| Use Case | Stopping when a goal is reached | Skipping unwanted values |
4. Real-World Example: Search System
Imagine searching for a specific ID in a list. Once found, there is no need to keep checking the rest of the items.
database = [101, 202, 303, 404, 505]
search_id = 303
for item in database:
if item == search_id:
print(f"ID {item} found! Stopping search...")
break
print(f"Checking ID {item}...")
5. Pass Statement vs. Break/Continue
While break and continue change the logic, pass is just a placeholder that does nothing.
for x in [0, 1, 2]:
if x == 1:
pass # Nothing happens here
print(x)