Python break statement
The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C.
The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in Python is as follows:
#!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter var = 10 # Second Example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: break print "Good bye!"
When the above code is executed, it produces following result:
Current Letter : P Current Letter : y Current Letter : t Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye!