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

Just the break keyword in the line and nothing else.

Examples

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

Output

1
2
3

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)

Output

1
2
3

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)

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.