Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - BREAK


'Break' as the name suggests, is used to break out of a loop(i.e. 'for loop' or 'while loop') before its execution is complete.


To make it a little simpler, let us take the below example.


'Break' with 'while loop'


Say you have a 'while loop' that is used to print the numbers from 1 to 6.


Example :


x = 1 
while x <= 6:
    print(x)
    x = x + 1 


Output :



  1
  2
  3
  4
  5
  6

But let us say, you want to 'break' out of the 'while loop', if the value of 'x' is '4'.
i.e. You want to get out of the loop, right after printing 1, 2, 3 and 4.


And we can achieve it using 'break' statement.


Let us modify the above program using the 'break' statement.


Example :


x = 1 
while x <= 6:
    print(x)
    if x == 4:
        break;
    x = x + 1


Output :



  1
  2
  3
  4

And all we have done is placed an 'if' condition, right after the print statement, checking if the value of 'x' is equal to '4'. If so we break out of the loop.


if x == 4:
    break;

And the 'break' statement helps to get out of the 'while loop'.


Let us see another example of 'break' using the 'for loop'.


'Break' with 'for loop'


Say we have a 'for loop' that prints all the letters of a String (i.e. Hello World).


Example :


for x in "Hello World":
    print(x)


Output :



  H
  e
  l
  l
  o
  
  W
  o
  r
  l
  d

But let's say, we just want to print 'Hello'. And omit the 'World'.


And as we can see that 'Hello World' is separated by a space ( i.e. ' ').


Let us rewrite the program using 'break' statement.


Example :


for x in "Hello World":
    if x == ' ':
        break;
    print(x)


Output :



  H
  e
  l
  l
  o

And what we have done is, checked if the value of 'x' is a white space (i.e. ' '). Because 'Hello World' is separated by a space (i.e. ' ').


if x == ' ':
    break;

And came out of the 'for loop' with the 'break' statement, printing just 'Hello'.