Python break Statement
break is the keyword in Python used to terminate a loop immediately.
When the program reaches break , it immediately exits the current loop structure (whether for or while) and does not execute the remaining code in the loop.
Word meaning: break means "to break or interrupt" and is used to terminate a loop.
Basic syntax and parameters
break It is a standalone statement and requires no arguments.
Syntax format
while 条件:
if exit condition:
break
# Other code
Use Cases
- Exit early: exit the loop immediately when a specific condition is met.
- Stop searching: exit the search once the target is found.
- Exit an infinite loop: used with while True, exiting via break.
Example
Example 1: using break in a for loop
Example
Find the first even number in a list
numbers
=
[
1
,
3
,
5
,
6
,
7
,
8
,
9
]
for
num
in
numbers:
if
num %
2
==
0
:
(
f
"Found the first even number: {num}"
)
break
(
"Search finished"
)
Expected output:
找到第一个偶数: 6
搜索结束
Code analysis:
- Iterate over the list and exit immediately after finding the first even number.
- Do not continue traversing the remaining elements.
Example 2: using break in a while loop
Example
Accumulate until the total exceeds 100
total
=
0
i
=
1
while
True
:
total +
=
i
if
total
100
:
(
f
"When i = {i}, the total first exceeds 100"
)
break
i +
=
1
(
f
"Total: {total}"
)
Output: Total: 105
Expected output:
Exit the loop immediately when the total exceeds 100.
Example 3: break in nested loops
Example
Nested loops: break only exits the inner loop
for
i
in
range
(
1
,
4
)
:
for
j
in
range
(
1
,
4
)
:
if
i
==
2
and
j
==
2
:
break
Only exit the inner loop
(
f
"({i}, {j})"
,
end
=
" "
)
(
)
Newline
Expected output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 3)
(3, 1) (3, 2) (3, 3)
Code analysis:
- break only exits the innermost loop containing it.
- The outer loop continues to execute.
Example 4: using break with else
Example
break causes else not to execute
for
i
in
range
(
5
)
:
if
i
==
3
:
(
"Target found, exiting early"
)
break
(
i
)
else
:
(
"Loop ended normally, target not found"
)
(
"---"
)
Ends normally (no break)
for
i
in
range
(
5
)
:
(
i
)
else
:
(
"Loop ended normally, else executed"
)
Expected output:
0
1
2
找到目标,提前退出
---
0
1
2
3
4
循环正常结束,else 执行
In a for-else or while-else structure, break causes the else clause not to execute.
Python3 loop statements