Python Basics — break, continue, pass
break, continue, pass
These three keywords give you fine-grained control over loop execution — exit early, skip iterations, or leave a placeholder.
break — Exit the Loop
break immediately terminates the innermost loop:
for num in range(1, 10):
if num == 5:
print("Found 5! Stopping.")
break
print(num)
Output:
1
2
3
4
Found 5! Stopping.
Searching for an Item
names = ["Alice", "Bob", "Charlie", "Diana"]
target = "Charlie"
for name in names:
if name == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found.")
Output:
Found Charlie!
Breaking from while
while True:
command = input("Enter command (quit to exit): ")
if command == "quit":
break
print(f"Running: {command}")
continue — Skip to Next Iteration
continue skips the rest of the current iteration and moves to the next one:
for num in range(1, 11):
if num % 2 == 0:
continue # Skip even numbers
print(num)
Output:
1
3
5
7
9
Filtering While Processing
scores = [85, -1, 92, 0, 78, -5, 95]
total = 0
count = 0
for score in scores:
if score < 0:
continue # Skip invalid scores
total += score
count += 1
print(f"Average: {total / count:.1f}") # Average: 62.5
pass — Do Nothing (Placeholder)
pass is a no-op statement. It does nothing but prevents a SyntaxError where Python expects a statement:
for i in range(5):
pass # TODO: implement later
Common Uses for pass
# Placeholder for a function
def process_data():
pass # Will implement later
# Placeholder for a class
class MyCustomError(Exception):
pass
# Placeholder for a condition
if True:
pass # Nothing to do in this case
pass vs continue
# pass — does nothing, continues to next statement in body
for i in range(3):
if i == 1:
pass
print(i) # Prints 0, 1, 2
# continue — skips rest of body, goes to next iteration
for i in range(3):
if i == 1:
continue
print(i) # Prints 0, 2
Comparison Table
| Keyword | Effect | Use Case |
|---|---|---|
break |
Exit the loop entirely | Found what you need, stop searching |
continue |
Skip to next iteration | Skip invalid data, filter during iteration |
pass |
Do nothing | Placeholder for future code |
Loop-else Interaction with break
The else block of a for or while loop runs only when the loop exits normally (without break):
# break triggers — else does NOT run
for n in [2, 3, 4, 5, 6]:
if n == 4:
print("Found 4")
break
else:
print("4 not found")
Output:
Found 4
# No break — else runs
for n in [2, 3, 5, 6]:
if n == 4:
print("Found 4")
break
else:
print("4 not found")
Output:
4 not found
Prime Number Checker Using for-else
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 # Divisible — not prime
return True
# Test
for num in range(2, 20):
if is_prime(num):
print(num, end=" ")
Output:
2 3 5 7 11 13 17 19
Practical Example: Input Validation with continue
entries = []
while len(entries) < 3:
value = input(f"Enter number {len(entries) + 1} of 3: ")
if not value.strip():
print(" Empty input — skipped!")
continue
try:
num = float(value)
except ValueError:
print(f" '{value}' is not a number — skipped!")
continue
entries.append(num)
print(f"\nYour numbers: {entries}")
print(f"Average: {sum(entries) / len(entries):.2f}")
Summary
breakexits the loop immediatelycontinueskips to the next iterationpassis a placeholder that does nothingbreakprevents the loop’selsefrom runningcontinuedoes NOT affectelse— onlybreakdoes- Use
passduring development as a stub for unfinished code
Next up: range(), enumerate(), zip() →