Javatpoint Logo
Javatpoint Logo

Python break statement

The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given condition. The syntax of the break statement in Python is given below.

Syntax:

Example 1 : break statement with for loop

Code

Output:

Item matched
Found at location 2

In the above example, a list is iterated using a for loop. When the item is matched with value 4, the break statement is executed, and the loop terminates. Then the count is printed by locating the item.

Example 2 : Breaking out of a loop early

Code

Output:

p
y
t
h

When the character is found in the list of characters, break starts executing, and iterating stops immediately. Then the next line of the print statement is printed.

Example 3: break statement with while loop

Code

Output:

0  1  2  3  4  5  6  7  8  9  came out of while loop

It is the same as the above programs. The while loop is initialised to True, which is an infinite loop. When the value is 10 and the condition becomes true, the break statement will be executed and jump to the later print statement by terminating the while loop.

Example 4 : break statement with nested loops

Code

Output:

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.

There are two nested loops in the above program. Inner loop and outer loop The inner loop is responsible for printing the multiplication table, whereas the outer loop is responsible for incrementing the n value. When the inner loop completes execution, the user will have to continue printing. When 0 is entered, the break statement finally executes, and the nested loop is terminated.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA