Python Break

What is Break statement in Python ?

Break statement in Python is used when you want to stop/terminate the flow of the program using some condition. Python Break

Assume that you want to exit from for loop & while loop you can use the break statement to exit a loop in Python.

using break statement in while loop:

#using break statement in while loop
n = 1
while n < 10:
  print(n)
  if n == 5:
    break
  n += 1
1
2
3
4
5

using break statement in for loop:

#using break statement in for loop
for n in range(10):
  if n > 5:
    break
  print(n)
0
1
2
3
4
5

name = 'Fullstackadda'

for letter in name:
    print(letter)
    if letter == 's':
        break
else:
    print("S letter not found")       #if no s letter in the 'name' it will print
F
u
l
l
s

Use of break Statement ?

Break statement in Python is used when you want to stop/terminate the flow of the program using some condition.

Let’s say that you have to find first prime number between 1 and 100.

So you will write a loop which starts from 2 and 100. But you found that 2 is a prime number. Here If we don’t terminate the loop when we find 2, the loop will continue up-to 100. Your program will do 98 waste executions which means a lot of time is wasted along with power. What if its not 100 it is may be a billions. Can you imagine how much time it will take.

That’s why we need to terminate a loop and it is possible by BREAK statement.

python break
  1. Break statement in Python is used when you want to stop/terminate the flow of the program using some condition.