Break Statement in Python Programming | Python Programming

Break Statement in Python: As we have discussed before for-loop and while-loop, we learnt that when we have to execute iteration over a sequence repeatedly as long as the condition remains True. We mainly use these loops to find an element or result in our sequence.

But when our sequence is found we need to stop the execution of the loop. For that purpose we use break-statement.

Flow Diagram of execution of break statement

break in python

ExampleSuppose we have a list x=[1,2,3,4,5]. And now we are searching that, do our list contains element 3?Program. No doubt we will use for-loop or while-loop to find out. But the for-loop will execute till last, see example:

# break-statement example
x = [1,2,3,4,5]
for i in x:
    print(i)

# output
# 1
# 2
# 3
# 4
# 5

Here we can easily observe that we are looking to find the existence of 3 in our sequence. And we successfully find that one. But the loop still executed even after finding the element. We need to stop the execution when our required element found.

Here we will use the break statement. Below is the complete example of break statement with syntax.

#break-statement example 
x = [1,2,3,4,5] 
for i in x:
    print(i)
    if(i==3):
        print("Number "+str(i)+" found") #here str() function used to convert  
                                         #integer type value to string.
        break                            #here break is used to terminate the loop when result found

# output
# 1
# 2
# 3
# Number 3 found

NOTEBreak statement is always used with if-statement for its successful execution. Else if we use the break statement alone, then it will terminate the loop at the first execution step.