(toc)
In Python, break
, continue
, and pass
are control flow statements that manage how loops behave. They allow you to exit loops, skip iterations, or write placeholders in your code.
1. The break
Statement
The break
statement is used to exit a loop prematurely. When executed, the loop ends, and the program continues with the next block of code outside the loop.
Syntax
for/while condition: if some_condition: break # Code to execute
Example: Breaking a for
Loop
for num in range(1, 6): if num == 3: print("Breaking the loop!") break print(num)
Output:
1 2 Breaking the loop!
Example: Breaking a while
Loop
count = 0 while count < 5: if count == 3: print("Breaking the loop!") break print(count) count += 1
Output:
0 1 2 Breaking the loop!
2. The continue
Statement
The continue
statement is used to skip the rest of the current iteration and move on to the next iteration in the loop. The loop does not terminate, but the code after continue
in the current iteration is ignored.
Syntax
for/while condition: if some_condition: continue # Code to execute
Example: Skipping a Value in a for
Loop
for num in range(1, 6): if num == 3: print("Skipping 3!") continue print(num)
Output:
1 2 Skipping 3! 4 5
Example: Skipping Odd Numbers in a while
Loop
count = 0 while count < 6: count += 1 if count % 2 != 0: # Skip odd numbers continue print(count)
Output:
2 4 6
3. The pass
Statement
The pass
statement does nothing and is used as a placeholder. It is useful when you need to write code later but want to avoid syntax errors in an empty block. Unlike break
or continue
, pass
doesn’t alter the flow of the loop.
Syntax
if condition: pass # Code continues here
Example: Placeholder in a Loop
for num in range(1, 6): if num == 3: pass # Placeholder for future logic print(num)
Output:
1 2 3 4 5
Example: Placeholder in an if
Statement
age = 18 if age >= 18: pass # Logic for adults will be added later else: print("Underage!")
Output:
(nothing happens because `pass` does nothing)
Comparison of break
, continue
, and pass
Statement | Purpose | Example Usage |
---|---|---|
break |
Exit the loop entirely. | Exit a search after finding a match. |
continue |
Skip the current iteration and move to the next. | Skip unwanted values (e.g., odd numbers). |
pass |
Do nothing; serves as a placeholder. | Write structure for future logic. |
Example Using All Three Statements
for num in range(1, 6): if num == 2: pass # Placeholder, does nothing elif num == 4: continue # Skip number 4 elif num == 5: break # Exit the loop when number 5 is reached print(num)
Output:
1 2 3