AlphaCodingSkills

Python - Break Statement


Advertisements

Previous Page Next Page

Python Break statement

The break statement in python 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


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

Output

1
2
3
4

Break statement with For loop


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

Output

red
blue
green

Break statement with Nested loop

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

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

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

Output

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

# output of nested loop with break statement
10
100
20
200
30
300





Previous Page Next Page