Break

 When working with loops, sometimes we may want to exit the entire loop when one certain condition is met. To do that, we use the break keyword.


Example

j = 0

for i in range(5):

    j = j + 2

    print('i = ', i, ' , j = ', j

    if j == 6: break


Output

i = 0 , j = 2

i = 1 , j = 4

i = 2 , j = 6


Without the break keyword, the program should loop from i = 0 to i = 4 because we used range(5). However with the break keyword, the program ends prematurely at i = 2. This is because when i = 2, j reaches the value of 6 and the break keyword causes the loop to end.

No comments:

Post a Comment