I. Overview of Loop Control Statements
In Python, loops are responsible for repeatedly executing code, while loop control statements are responsible for changing the normal execution path of a loop.
Normally, a loop executes in the following order:
- Check the loop condition or get the next element.
- Execute the loop body.
- Enter the next iteration.
- Exit when the loop condition is no longer satisfied or the iterable is exhausted.
But real programs often need to handle more situations:
- Stop searching after the target data is found.
- Skip the current record when encountering data that does not meet the condition.
- Temporarily leave a code block that has not yet been implemented.
- Terminate a task early under specific conditions.
Python provides three statements to handle these situations:
| Statement | Meaning | Core function |
|---|---|---|
break |
Interrupt | Immediately terminate the current loop |
continue |
Continue | Skip the remaining code in the current iteration |
pass |
Placeholder | Do nothing and continue executing subsequent code |
They all look simple, but their execution effects are completely different.
1. Core Differences Between the Three
flowchart TD
A["Execute loop body"] --> B{"Which control statement is encountered?"}
B -->|break| C["Terminate the current loop"]
B -->|continue| D["Skip the remaining code in this iteration"]
B -->|pass| E["Perform a no-op"]
B -->|Normal statement| F["Continue executing subsequent code"]
D --> G["Enter the next iteration"]
E --> F
F --> G
G --> H["Re-evaluate the condition or get the next element"]
C --> I["Execute the code after the loop"]
H --> A
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
II. break: Terminate the Loop Immediately
break is used to end a loop early. When the program reaches break, it immediately exits the nearest enclosing loop and no longer executes the remaining iterations of that loop.
break can be used to:
- Stop searching after the target element is found.
- End computation early after a certain condition is met.
- Terminate interaction when the user enters an exit command.
- End the loop when a situation occurs that cannot be processed further.
1. Basic Syntax
for 变量 in 可迭代对象:
if 终止条件:
break
循环体
Or:
while 条件:
if 终止条件:
break
循环体
break must be inside a loop; it cannot be used alone in an ordinary code block, nor can it be used directly in non-loop structures such as functions or conditional statements.
2. Using break in a for Loop
Example: Iterate over numbers and stop when 5 is encountered.
for number in range(1, 10):
if number == 5:
break
print(number)
Output:
1
2
3
4
Execution process:
- Get the number 1 and execute the loop body.
- Get the number 2 and execute the loop body.
- Get the number 3 and execute the loop body.
- Get the number 4 and execute the loop body.
- Get the number 5; the termination condition is met.
- Execute
break, immediately exiting the loop.
The print() after the number 5 is not executed, and the numbers 6 through 9 are no longer iterated over.
3. Using break in a while Loop
count = 0
while True:
count += 1
if count > 5:
break
print(count)
Output:
1
2
3
4
5
Here, while True is used to create a loop that keeps running, with break providing an explicit exit condition.
This pattern is often used in interactive programs, command-line tools, and continuous processing tasks.
4. Using break to Search Data
Suppose you need to find a specific user in a list of users:
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Charlie"},
{"id": 4, "name": "David"}
]
target_id = 3
target_user = None
for user in users:
if user["id"] == target_id:
target_user = user
break
print(target_user)
Output:
{'id': 3, 'name': 'Charlie'}
Once the target user is found, there is no point in continuing to iterate, so break is used to end the loop early.
If the list is very large, this approach reduces the number of unnecessary comparisons.
5. Using break to Implement User Exit
while True:
command = input("请输入命令(输入 exit 退出):")
if command == "exit":
print("程序结束")
break
print(f"正在执行:{command}")
When the user enters exit, the loop terminates immediately.
Note that break is only responsible for ending the current loop. If the loop involves files, network connections, or other resources, you still need to ensure they are released properly through mechanisms such as with and finally.
6. Execution Flow of break
flowchart TD
A["Enter the loop"] --> B["Execute the current iteration"]
B --> C{"Is the break condition met?"}
C -->|No| D["Continue executing the loop body"]
D --> E["Proceed to the next iteration"]
E --> B
C -->|Yes| F["Execute break"]
F --> G["Exit the current loop immediately"]
G --> H["Execute the code after the loop"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
7. break Only Terminates the Innermost Loop
This is a very important rule when using break.
When loops are nested, break only terminates the innermost loop it is currently in; it does not automatically end all the outer loops.
For example:
for i in range(3):
print(f"外层循环:{i}")
for j in range(3):
if j == 1:
break
print(f"内层循环:{j}")
Output:
外层循环:0
内层循环:0
外层循环:1
内层循环:0
外层循环:2
内层循环:0
Execution process:
- The outer loop runs for the first time,
i = 0. - When the inner loop reaches
j = 1,breakis triggered. - The inner loop ends, and the outer loop continues.
- The outer loop proceeds to the next round, repeating the process above.
Therefore, the scope of break is the innermost loop it resides in.
8. How to Exit Multiple Nested Loops
If you need to exit multiple levels of loops at the same time, you can use the following approaches.
Approach 1: Use a flag variable
found = False
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
found = True
break
if found:
break
print("搜索结束")
After the inner loop finds the target, it sets found to True, and then the outer loop also exits based on this flag.
Method 2: Encapsulate the loop in a function and use return
def search():
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
return i, j
return None
result = search()
print(result)
Output:
(2, 3)
return directly terminates the entire function, so it can exit multiple nested loops inside the function all at once.
Method 3: Use exceptions for special control flow
In some complex control flows, you can also define a dedicated exception to exit a deeply nested structure, but using the exception mechanism merely to exit loops is generally not recommended.
Usually, a flag variable or function encapsulation is preferred.
9. break and the Loop's else Clause
Python's for and while both support an else clause.
A very important rule is:
When a loop is terminated early by break, the loop's else clause is not executed.
For example:
for number in range(5):
if number == 3:
break
print(number)
else:
print("循环正常结束")
Output:
0
1
2
Because the loop is terminated early by break, the else is not executed.
If break is not triggered:
for number in range(3):
print(number)
else:
print("循环正常结束")
Output:
0
1
2
Loop ended normally
The else clause is suitable for search tasks: if the loop finishes iterating normally, it means the target was not found through break.
numbers = [10, 20, 30, 40]
target = 50
for number in numbers:
if number == target:
print("找到目标")
break
else:
print("没有找到目标")
Output:
Target not found
III. continue: Skip the Current Iteration
continue is used to skip the remaining code in the current loop iteration that has not yet been executed, and proceed directly to the next iteration.
It does not terminate the entire loop, nor does it exit the loop structure.
Common use cases:
- Skip data that does not meet the condition.
- Ignore null values or invalid records.
- Filter out elements that do not need to be processed.
- Skip specific items in batch tasks.
1. Basic Syntax
for 变量 in 可迭代对象:
if 跳过条件:
continue
循环体
Or:
while 条件:
if 跳过条件:
continue
循环体
When the condition is true, the program executes continue, and the remaining code in the current iteration is no longer executed.
2. Using continue in a for Loop
Example: print the odd numbers from 1 to 10.
for number in range(1, 11):
if number % 2 == 0:
continue
print(number)
Output:
1
3
5
7
9
Execution process:
- Get the number 1; the condition is false, so print 1.
- Get the number 2; the condition is true, so execute
continue. - Skip the remaining code in the current iteration.
- Proceed to the next iteration and continue processing the number 3.
- Repeat until all numbers have been traversed.
3. Using continue to Filter Data
Suppose you need to process a batch of scores and only count the valid scores:
```python scores = [90, -1, 85, 0, 95, -1, 88] valid_scores = [] for score in scores: if score < 0: continue valid_scores.append(score) print(valid_scores) ```Output:
[90, 85, 0, 95, 88]
Here negative numbers represent invalid data, so continue is used to skip them.
Note that 0 is not skipped, because the code only treats values less than 0 as invalid.
4. Using continue to Skip Empty Data
When processing text files or batch data, you often need to skip empty lines:
lines = [
"Python",
"",
"Java",
" ",
"Go"
]
for line in lines:
if not line.strip():
continue
print(line)
Output:
Python
Java
Go
strip() removes whitespace from both ends of a string, so both empty strings and strings containing only whitespace can be filtered out.
5. Using continue in a while Loop
while differs from for: you usually need to maintain the loop state manually.
Therefore, when using continue in a while loop, pay special attention to where the loop variable is updated.
Incorrect example:
count = 0
while count < 5:
if count == 2:
continue
print(count)
count += 1
Execution process:
countstarts at 0.- When
countis 0 or 1, it prints normally and increments. - When
countequals 2, the skip condition is met. continueexecutes, skippingcount += 1.countstays at 2 forever, and the loop condition is always true.
The result is an infinite loop.
Correct approach 1: update the loop variable first.
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
Output:
1
2
4
5
Correct approach 2: put the update before the conditional branch.
count = 0
while count < 5:
if count == 2:
count += 1
continue
print(count)
count += 1
Output:
0
1
3
4
Both approaches avoid an infinite loop.
The core principle is: make sure every path that might execute continue does not miss a necessary state update.
6. Execution Flow of continue
flowchart TD
A["Enter loop"] --> B["Execute current iteration"]
B --> C{"Is the continue condition met?"}
C -->|No| D["Execute remaining loop body code"]
D --> E["Proceed to next iteration"]
C -->|Yes| F["Execute continue"]
F --> G["Skip remaining code in this iteration"]
G --> E
E --> H["Re-evaluate the condition or get the next element"]
H --> A
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
7. continue Does Not Skip the Entire Nested Loop
Like break, continue only affects the innermost loop.
For example:
for i in range(3):
for j in range(3):
if j == 1:
continue
print(i, j)
Output:
0 0
0 2
1 0
1 2
2 0
2 2
When j in the inner loop equals 1, only the current inner iteration is skipped, and the inner loop continues with the next value.
The outer loop is unaffected.
8. continue and for-else
continue does not terminate the loop early, so it does not prevent the else clause from executing after the loop finishes normally.
for number in range(5):
if number % 2 == 0:
continue
print(number)
else:
print("循环正常结束")
Output:
1
3
循环正常结束
Although some iterations are skipped, the loop eventually runs out normally, so the else still executes.
4. pass: The No-Op Placeholder
pass is Python's no-op statement.
It performs no actual operation and does not change the program's execution flow.
Its main purpose is to satisfy Python's syntactic requirements, keeping a code block valid while it has not yet been implemented.
Common use cases:
- Temporarily reserving functions that are not yet implemented.
- Creating the structural skeleton of a class.
- Reserving a conditional branch.
- Writing program prototypes.
- Temporarily filling the place of a loop or exception-handling block.
1. Basic Syntax
pass
pass can appear in any code block that requires a statement.
For example:
if condition:
pass
for item in items:
pass
while condition:
pass
2. Using pass in Conditional Statements
Python conditional statements must contain a valid code block.
If you don't need to perform any operation for the time being, you can use pass:
age = 18
if age >= 18:
pass
else:
print("未成年")
Here, when the condition is met, nothing is done, and the program continues executing the code that follows.
If you write it directly as:
if age >= 18:
else:
print("未成年")
the program will raise a syntax error, because the if is missing a valid code block.
3. Using pass in Loops
for number in range(5):
if number == 2:
pass
print(number)
Output:
0
1
2
3
4
When number equals 2, pass performs no operation, but the program still continues to execute the print() that follows.
Therefore, pass is not the same as continue.
4. Using pass in Functions
During development, you may design the function interface first and fill in the concrete implementation later.
def login():
pass
def register():
pass
def logout():
pass
These functions currently have no concrete implementation, but the code runs fine.
When you call a function that has no explicit return value, Python returns None by default.
result = login()
print(result)
Output:
None
5. Using pass in Classes
You can use pass to define classes that have no implementation for now:
class User:
pass
class Product:
pass
class Order:
pass
This is helpful for a development approach in which you first establish the project structure and then gradually add attributes and methods.
6. Using pass in Exception Handling Blocks
try:
number = int("abc")
except ValueError:
pass
After the program catches the ValueError, it performs no handling operation.
However, in real-world engineering, it is not advisable to ignore exceptions arbitrarily.
At minimum, logging the error is preferable:
try:
number = int("abc")
except ValueError as error:
print(f"数据转换失败:{error}")
If you really intend to ignore a certain type of exception, you should also clearly explain the reason, so as not to hide real problems.
7. Execution Flow of pass
flowchart TD
A["Enter code block"] --> B["Execute pass"]
B --> C["Do nothing"]
C --> D["Continue executing subsequent statements"]
D --> E["Continue with the original control flow"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
V. Comparison of break, continue, and pass
All three statements can appear inside a loop, but their effects on control flow are completely different.
1. Comparison of Core Behaviors
| Aspect | break | continue | pass |
|---|---|---|---|
| Performs an actual operation | Yes, changes control flow | Yes, changes control flow | No |
| Ends the current iteration | Yes | Yes | No |
| Ends the entire current loop | Yes | No | No |
| Enters the next loop iteration | No | Yes | Determined by normal flow |
| Affects the outer loop | Does not directly affect it | Does not directly affect it | Does not affect it |
| Can be used outside a loop | No | No | Yes |
| Typical use | Early termination | Skip current data | Code placeholder |
2. Different Effects in the Same Code
Use an example to intuitively understand the differences among the three.
Using break:
for number in range(5):
if number == 2:
break
print(number)
Output:
0
1
When the number equals 2, the entire loop terminates.
Using continue:
for number in range(5):
if number == 2:
continue
print(number)
Output:
0
1
3
4
When the number equals 2, only the current iteration is skipped.
Using pass:
for number in range(5):
if number == 2:
pass
print(number)
Output:
0
1
2
3
4
When the number equals 2, no additional operation is performed, and the subsequent code still executes.
3. Execution Behavior Comparison Table
| Current Number | break | continue | pass |
|---|---|---|---|
| 0 | Prints 0 | Prints 0 | Prints 0 |
| 1 | Prints 1 | Prints 1 | Prints 1 |
| 2 | Exits the loop | Skips printing | Prints normally |
| 3 | Not executed further | Prints 3 | Prints 3 |
| 4 | Not executed further | Prints 4 | Prints 4 |
4. How to Choose
You can quickly decide with three questions:
- Do you still need to continue processing the following elements? If not, consider
break. - Do you just not want to process the current element? If so, consider
continue. - Does the current code block temporarily have no implementation content, but a statement is syntactically required? Consider
pass.
VI. Combining Loop Control with else
To understand loop control statements, you also need to master how they combine with else.
1. break and else
break terminates the loop early, so it skips else.
for number in range(5):
if number == 2:
break
else:
print("正常结束")
Output: none.
2. continue and else
continue only skips the current iteration, and the loop can still finish normally.
for number in range(5):
if number == 2:
continue
print(number)
else:
print("正常结束")
Output:
0
1
3
4
正常结束
3. pass and else
pass does not change the loop's normal execution path.
for number in range(3):
if number == 1:
pass
print(number)
else:
print("正常结束")