Python break is an in-built function as well as a control statement in python which terminates the loop the user is in. The mode of the flow goes directly to the code statement leaving the loops. Break only terminates the inner most statement like in case of nested loop. Break would not terminate the whole loop, but only the inside loop. Hence, it works one by one. Break is used in cases of loops only, mostly if-else loop.
Below is a program to understand the use of break in python:
for x in "Welcome to Developer Helps": if x == "o": break print(x)
The output of the above python program will be:
W e l c
In this program, the user wants to terminate the loop as soon as it reaches ‘o’. Hence the string “welcome to Developer Helps” is terminated after reaching o and the output comes out to be ‘w e l c’.
The user uses the break statement when he wants to search for a number using iterations. In case the user wants to search for say, number 10 in an array. He can follow the code below where iterations will be done in the array and break function will work once number 10 is found in the list.
for x in [11, 30, 9, 4, 5, 10, 19, 16]: print(x) if(x==10): print("The number 10 is found") print("Terminating the loop") break
The output of this python code will be:
11 30 9 4 5 10 The number 10 is found Terminating the loop
Python Break vs Continue
Both break and continue are control statements in python. As we have discussed, in case of break the loop terminates and the flow is shifted to either the next loop or the statement. Continue function on the other hand doesn’t terminate the loop, but it skips the current loop and moves forward to the other. Other than these two, there is another control statement pass. It executes when user wants to run an empty code block.
Let us see the program below to understand how break and continue works together:
print ("In case of break function") for x in "Welcome to Developer Helps": if x == "o": break print(x) print ("In case of continue function") for y in "Welcome to Developer Helps": if y == "o": continue print(y)
The output of the program for checking break vs continue in python is:
In case of break function W e l c In case of continue function W e l c m e t D e v e l p e r H e l p s
Python break out of function
This is a built in function which helps to come out of the loop in the code using some external agent. It is generally written after the loop condition. Hence, to clear the term, break is written out of the function code to execute.
Below is a program to understand how break out of function works.
num = 0 for num in range(10): if num == 3: break print('The Number is ' + str(num)) print('The number is out of loop')
The output of the program will be:
The Number is 0 The Number is 1 The Number is 2 The number is out of loop