Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python break Statement

Python break Statement

Python3 Loop Statements Python3 loop statements


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


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

:

       

print

(

f

"Found the first even number: {num}"

)

       

break

print

(

"Search finished"

)

Expected output:

找到第一个偶数: 6
搜索结束

Code analysis:

  1. Iterate over the list and exit immediately after finding the first even number.
  2. 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

:

       

print

(

f

"When i = {i}, the total first exceeds 100"

)

       

break

    i +

=

1

print

(

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

       

print

(

f

"({i}, {j})"

,

end

=

" "

)

   

print

(

)

 

Newline

Expected output:

(1, 1) (1, 2) (1, 3)
(2, 1) (2, 3)
(3, 1) (3, 2) (3, 3)

Code analysis:

Example 4: using break with else

Example

break causes else not to execute

for

i

in

range

(

5

)

:

   

if

i

==

3

:

       

print

(

"Target found, exiting early"

)

       

break

   

print

(

i

)

else

:

   

print

(

"Loop ended normally, target not found"

)

print

(

"---"

)

Ends normally (no break)

for

i

in

range

(

5

)

:

   

print

(

i

)

else

:

   

print

(

"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 Python3 loop statements