How to PROPERLY use break statement in Python [Easy Examples]


Written by - Deepak Prasad

Python Break Statement

In Python break is used to exit a for loop or a while loop when certain condition is satisfied. Note that break statement will only come out from the inner most loop it is used in. However, in case of nested loops, it will continue executing the outer loop with the next iterable. When break statement is used with the loop containing else clause, the block of statements in else clause is not executed if the loop terminates due to break statement.

 

Example 1 - break from while loop

The example here iterates over the range of numbers from 1 to 10 and prints its value. However, if it reaches the number divisible by 5, it will break the loop. Note that in this case, the statement inside the else block will not be printed as the loop stops iterating when the value reaches 5.

# Initializing
i=1

# Iterating while loop
while i<10:
    # loop terminates if the value of i reaches number divisible by 5
    if(i%5==0):
        break
    print(i)
else:
    print("This statement gets printed only if the for loop terminates after iterating for given number of times and not because of break statement")

Output

1
2
3
4

 

Example 2 - break from for loop while iterating over the list

When you want to iterate over the sequence one way is to iterate using the for loop given below that gives the position of the desired element. Here, we are performing linear search to search the element whose value is "Mango". The example below iterates over the list of fruits and returns the position of fruit "Mango" and terminates the loop once the element is found.

# Initializing
l1=['India','Nepal','Srilanka','China','Australia']
for country in l1:
	if country == 'China':
		break
	else:	
		print (country)

Output

India
Nepal
Srilanka

 

Example 4 - Fibonacci Series using while loop and break statement 

In this example, we are using while loop to print the Fibonacci series till the end value scanned from the user.

#Initializing 
fib=0
f1=0
f2=1
print(f1," ",f2)
fibo=0
endvalue=int(input("Enter the end value"))

# Using break statements
while True:
     # Checking for the end value
    if fibo>endvalue:
        break
     # computing the fibonacci series values
    else:
        fibo=f1+f2
        print(fibo)
        f1=f2
        f2=fibo

Output

0   1
Enter the end value
10
1
2
3
5
8
13

 

Example 5 - While with else block and break statement

In the example given below, we are having a counter that prints the number from 101 to 104 if and only if it is not divisible by 5. And, once it reaches the value, the loop terminates and else clause gets executed if loop is terminated because of false condition. Here, when the count reaches 105, the while condition is false and hence else block gets executed.

# Initializing
count=101
while(count<105):
     if(count%5==0):
        break
     print(count)
     count += 1
else:
     print("count value reached")

Output

101
102
103
104
count value reached

 

Example 6 - Constructing Dictionary from two list

In the example given below, We have two list containing the name of students and their score respectively. Here, we will read the value from the two lists and construct the dictionary out of this lists with the condition that if the score is found to be greater than 90 for any student, loop will terminate.

l1=['Ram', 'Rohan', 'Rishi', 'Radha']
l2=[82,52,95,10]
d={}
i=0
while i<len(l1) and i <len(l2): if(l2[i] > 90):
        break
    d.update({l1[i]:l2[i]})
    i+=1
else:
    print("Dictionary constructed successfully")
print("Retrieving values from Dictionary")
print(d)

Output

Retrieving values from Dictionary
{'Ram': 82, 'Rohan': 52}

 

Example 7 - While loop inside for loop

In the example given below, we will print the strings stored in the list using the while loop and iterate over the list using for loop. Once, we encounter $ symbol in the particular string of a list, it will simply skip that word and continue with the next word.

# Initializing
s=['Welcome', 'to', 'the', 'world', 'of', '$dollar', 'Python']
# iterate loop till the last character
for word in s:
    i=0
     # Iterating word by word
    while i < len(word):
    # break loop if current character is dollar $
        if word[i]== '$':
            break
    # print current character
        print(word[i], end=' ')
        i = i + 1

Output

W e l c o m e t o t h e w o r l d o f P y t h o n

 

Example 8 - Using break statement inside nested multiple loops

In the example given below, we are getting the marks of two students opted for different number of subjects and each subject has three sections. Here, the inner most loop terminates if student scores marks less than 50 for each section. Whereas, the subject loop terminates if total score of a subject for a student is less than 170. Hence, student is eligible only if he/she scores at least 50 in each section and at least 170 in each subject.

noOfStudents=2
for i in range(0,noOfStudents):
    subject=1
    subCount=1
    while(subject==1 and subCount <=3):
        secCount=1
        sum=0
        while(secCount<=3):
            print("Enter marks of subject for student",i,"--subject", subCount,"--section", secCount)
            marks=int(input())
            if(marks<50):
                print("You scored marks less than 50 for section. So you are not eligible to apply")
                break
            sum=sum+marks
            print("Sum is", sum)
            secCount+=1
        if(sum<170):
            print("Your  total score for subject is less than 100. So you are not eligible to apply")
            break
        print("Do you have any more subject for student ",i,"Press 1 for Yes and any other number for No")
        subject=int(input())
        subCount+=1

Output

Enter marks of subject for student 0 --subject 1 --section 1
50
Sum is 50
Enter marks of subject for student 0 --subject 1 --section 2
51
Sum is 101
Enter marks of subject for student 0 --subject 1 --section 3
48
You scored marks less than 50 for section. So you are not eligible to apply
Do you have any more subject for student  0 Press 1 for Yes and any other number for No
2
Enter marks of subject for student 1 --subject 1 --section 1
50
Sum is 50
Enter marks of subject for student 1 --subject 1 --section 2
50
Sum is 100
Enter marks of subject for student 1 --subject 1 --section 3
50
Sum is 150
Do you have any more subject for student  1 Press 1 for Yes and any other number for No
2

 

Example 9 - Using break to come out of multiple nested loops

In this example, we are printing multiplication table for a numbers less than 12 and result of multiplication less than 30.


rows = int(input("Enter the number of rows "))
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        # multiplication current column and row
        square = i * j
        print(i * j, end='  ')
        if(square > 30):
            break
    if(i>12):
        break
    print()

Output

Enter the number of rows 
15
1  
2  4  
3  6  9  
4  8  12  16  
5  10  15  20  25  
6  12  18  24  30  36  
7  14  21  28  35  
8  16  24  32  
9  18  27  36  
10  20  30  40  
11  22  33  
12  24  36  
13  26  39

 

Summary

The knowledge of control flow statement break is core to python programming language that is very useful to formulate a complex logic easily. You will frequently need to use the break statements  to prevent execution of block for certain set of values and build varied of applications. The knowledge of break in different scenarios and combinations helps solving the really complex task to a time efficient solution. In this tutorial, we covered the break statement with for loop, while loop, nested loops and different combinations of the loops along with an example to demonstrate the functionalities of break statement. All in all, this tutorial, covers everything that you need to know in order to understand and use the break in Python.

 

References

Control Flow statement
Python - `break` out of all loops
How can I break out of multiple loops? - python - Stack Overflow

 

Further Reading

Python while loop examples for multiple scenarios
Python for loop (10 easy examples with syntax)

 

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

X