Python break, continue, and pass
1. Python break Statement
Definition:
The break statement is used to terminate the loop prematurely, regardless of the loop condition.
Syntax:
for item in iterable:
if condition:
break
Example: Stop loop at a certain value
for i in range(1, 10):
if i == 5:
break
print("i =", i)
Output:
i = 1 i = 2 i = 3 i = 4
Explanation:
Loop exits when i == 5.
2. Python continue Statement
Definition:
The continue statement skips the current iteration and continues with the next one.
Syntax:
for item in iterable:
if condition:
continue
# rest of the code
Example: Skip even numbers
for i in range(1, 6):
if i % 2 == 0:
continue
print("Odd number:", i)
Output:
Odd number: 1 Odd number: 3 Odd number: 5
Explanation:
Even numbers (2 and 4) are skipped.
3. Python pass Statement
Definition:
The pass statement is a null operation—it does nothing. It is used as a placeholder for future code.
Syntax:
for item in iterable:
if condition:
pass # placeholder for future logic
Example: Use in unfinished block
for i in range(3):
if i == 1:
pass # logic to be implemented later
print("i =", i)
Output:
i = 0 i = 1 i = 2
Explanation:
Even though pass does nothing, the loop continues normally.
Comparison Table
Statement | Purpose | Affects Loop |
---|---|---|
break | Exits the loop completely | Yes |
continue | Skips the current iteration | Yes |
pass | Does nothing, used as a placeholder | No |