Python break statement is used to terminate the current loop and resumes execution at the next statement, just like the traditional break statement in C.
The most common use for Python break statement is when some external condition is triggered requiring a sudden exit from a loop. The break statement can be used in both Python while and for loops.
If you are using nested loops in Python, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
Syntax of break StatementThe syntax for a break statement in Python is as follows −
looping statement: condition check: breakFlow Diagram of break Statement
Following is the flowchart of the break statement −
break Statement with for loopIf we use break statement inside a for loop, it interrupts the normal flow of program and exit the loop before completing the iteration.
ExampleIn this example, we will see the working of break statement in for loop.
for letter in 'Python': if letter == 'h': break print ("Current Letter :", letter) print ("Good bye!")
When the above code is executed, it produces the following result −
Current Letter : P Current Letter : y Current Letter : t Good bye!break Statement with while loop
Similar to the for loop, we can use the break statement to skip the code inside while loop after the specified condition becomes TRUE.
ExampleThe code below shows how to use break statement with while loop.
var = 10 while var > 0: print ('Current variable value :', var) var = var -1 if var == 5: break print ("Good bye!")
On executing the above code, it produces the following result −
Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye!break Statement with Nested Loops
In nested loops, one loop is defined inside another. The loop that enclose another loop (i.e. inner loop) is called as outer loop.
When we use a break statement with nested loops, it behaves as follows −
The following program demonstrates the use of break in a for loop iterating over a list. Here, the specified number will be searched in the list. If it is found, then the loop terminates with the "found" message.
no = 33 numbers = [11,33,55,39,55,75,37,21,23,41,13] for num in numbers: if num == no: print ('number found in list') break else: print ('number not found in list')
The above program will produce the following output −
number found in list
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4