Python Tutorial Python Advanced Python References Python Libraries

Python break Keyword



The Python break keyword (statement) is used to terminate the program out of the loop containing it. If the break statement is used in a nested loop (loop inside loop), it will terminate innermost loop.

Break statement with While loop:

In the example below, break statement is used to get out of the while loop if the value of variable j becomes 5.

i=10
j=1
while (j < i):
    if (j == 5):
        break
    print(j)
    j = j + 1

The output of the above code will be:

1
2
3
4

Break statement with For loop:

Here, the break statement is used to get out of the for loop if the value of variable x becomes 'yellow'.

color = ['red', 'blue', 'green', 'yellow', 'black', 'white'] 
for x in color:
    if(x == 'yellow'):
        break
    print(x)

The output of the above code will be:

red
blue
green

Break statement with Nested loop:

In the example below, break statement terminates the inner loop whenever multiplier becomes 100.

# nested loop without break statement   
digits = [1, 2, 3] 
multipliers = [10, 100, 1000]
print("# nested loop without break statement")
for digit in digits:
    for multiplier in multipliers:
        print (digit * multiplier)

The output of the above code will be:

# nested loop without break statement
10
100
1000
20
200
2000
30
300
3000

# nested loop with break statement  
digits = [1, 2, 3] 
multipliers = [10, 100, 1000]
print("# nested loop with break statement")
for digit in digits:
    for multiplier in multipliers:
        if (multiplier == 100):
            break
        print (digit * multiplier)

The output of the above code will be:

# nested loop with break statement
10
20
30

❮ Python Keywords