Press ESC to close

Break Python

0 1349

Break in loops in Python – In this lesson we will study how to use the break statement in loops. This instruction is useful when we want to terminate the loop following a condition and usually go to the next code.

The break statement in Python, like in many other programming languages, allows you to exit the for or while loop immediately.

Break can be used in all loops, even nested loops. If used in nested loops, only the loop it is placed in will be terminated and other loops will continue as normal.

Break Python – first example with while

Let’s take a practical example immediately, with while loop.

Enter numbers and add them. As soon as you enter a negative number, you exit the while loop.

Here is a possible implementation of the proposed algorithm.


i = sum = 0

while i < 10:
    n = int(input('Insert a number: '))
    if n < 0:
        break
   sum += n
   i += 1

print('Sum is: ', sum)

In this example as soon as we insert a negative number we immediately exit the loop without adding it. In fact, break causes the immediate exit from the while loop.

Try this example in the online compiler, which you can find at this link: Python compiler online.

Break Python – second example with for

Let’s do the same example using the for this time. Also this time we insert the break when a condition occurs.

So here is a possible implementation:


sum = 0
for i in range(10):
    n = int(input('Insert a number: '))
    if n < 0:
        break
   sum += n
print('Sum is: ', sum)

As we can see also this time, when we insert a negative number, we get out of the loop.

Break Python - third example with for nested

In this example we use the break only in the innermost loop. We enter as a condition, when i equals 1 and j equals 3.

So here is a possible example:


'''
Break Python - FOR LOOP Nested
'''
for i in range(1,3):
    for j in range(1,5):
        print(j, end = '')
        if j == 3 and i == 1:
          break
    print()

In this lesson we have made some examples of breaks in Python, in the next lesson we will talk about continues.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Other stories

Python continue

Next Story

Exercises for Python

Previous Story