Python Break

Python Break statement

Python break statement is used to break a loop, even before the loop condition becomes false.

In this tutorial, we shall see example programs to use break statement with different looping statements.

Syntax

Following is the syntax of break statement.

break
Run this program

Just the break keyword in the line and nothing else.

Example 1: Break Statement with While Loop

In this example, we shall write a while loop to print numbers from 1 to 10. When when the loop is running to print 4, we shall break the loop.

Python Program

i = 1
while i <= 10 :
    if i == 4 :
        break
    print(i)
    i += 1
Run this program

Output

1
2
3

Example 2: Break Statement with For Loop and Range

In this example, we shall take the same scenario of breaking the loop when about to print 4. But here, we shall use for loop with range.

Python Program

for x in range(1, 11) :
    if x == 4:
        break
    print(x)
Run this program

Output

1
2
3

Example 3: Break Statement with For Loop and List

In this example, we shall iterate over list using for loop. When we get an element of 9, we shall break the loop.

Python Program

myList = [1, 5, 4, 9, 7, 2]

for x in myList :
    if x == 9:
        break
    print(x)
Run this program

Output

1
5
4

Summary

In this tutorial of Python Examples, we learned how to use break statement to end a loop execution, with the help of example programs.