Python – Break Statement

Python Break statement

When the condition is fulfilled, the break statement in Python is used to exit the programme from the loop containing it.

If the break statement is used in a nested loop (loop inside the loop), the innermost loop will be terminated once the break requirements are met.

Break statement with While loop

If the value of variable j becomes 4, the break statement is used to exit the while loop in the example below.

j=1
while (j < 10):
  if (j == 4):
    print("Getting out of the loop.")
    break
  print(j)
  j = j + 1

The output of the above code will be:

1
2
3
Getting out of the loop.

Break statement with For loop

If the value of variable x becomes ‘yellow,’ the break statement is used to exit the for loop.

color = ['red', 'blue', 'green', 'yellow', 'black', 'white'] 
for x in color:
  if(x == 'yellow'):
    print("Getting out of the loop.")
    break
  print(x)

The output of the above code will be:

red
blue
green
Getting out of the loop.

Break statement with Nested loop

When the multiplier reaches 100 in the example below, the break statement ends the inner loop.

# 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

Also Read: Java – Break Statement

Leave a Reply

Your email address will not be published. Required fields are marked *