Python break statement:

The break statement in Python is used to bring the control out of the loop when some external condition is triggered. The break statement breaks out of the innermost enclosing for or while loop.

Syntax :

The signature for the break statement is as shown below.

break

Flow diagram – break statement:

Flow Diagram - break statement

Python break Examples:

Example 1: In this example, we will demonstrate the break statement while printing a prime number less than 10.

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        print(n, 'is a prime number')

Output

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Example 2: In this case, we will use the break statement with a list items.

#Initializing 
l1=['Mumbai','Thane','Palghar','Ratnagiri']
for city in l1:
	if city == 'Thane':
		break
	else:	
		print (city)
	

Output

Mumbai

Example 3: In this example, We will use break statement while printing the fibonacci series till the number 10.

#Initializing 
fib=0
f1=0
f2=1
print(f1," ",f2)
fibo=0
# Using break statements
while True:
    if fibo<10:
        break
    else:
        fibo=f1+f2
        print(fibo)
        f1=f2
        f2=fibo

Output

0   1
1
2
3
5
8
13

References

Happy Learning 🙂

Leave A Comment