The break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has been completely iterated over.
An important note is that if you break out of a for or while loop, any loop else block is not executed.
Example 6.5. Using the break statement
#!/usr/bin/python # Filename : break.py while True: s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'Done'
$ python break.py Enter something : Programming is fun Length of the string is 18 Enter something : When the work is done Length of the string is 22 Enter something : if you wanna make your work also fun: Length of the string is 37 Enter something : use Python! Length of the string is 12 Enter something : quit Done
In this program, we repeatedly take the user's input and print the length of the input each time. We need to take care of the special condition where if the user enters the string quit, then we have to stop the loop. This is done by checking if the input is equal to the string quit and if so, then we use the break statement to quit the loop.
Remember that the break statement can be used with the for loop as well.