PYTHON - break Statement
Python - break Statement
Python break Statement
Pythonbreak statementis used to terminate the currentloopand resumes execution at the next statement, just like the traditionalbreak 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. Thebreak statementcan be used in both Pythonwhileandforloops.
If you are usingnested 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 Statement
The syntax for abreak statementin 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 loop
If we use break statement inside afor loop, it interrupts the normal flow of program and exit the loop before completing the iteration.
Example
In 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 thefor loop, we can use the break statement to skip the code insidewhile loopafter the specified condition becomes TRUE.
Example
The 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
Innested loops, one loop is defined inside another. The loop that enclose another loop (i.e. inner loop) is called asouter loop.
When we use a break statement with nested loops, it behaves as follows β
- When break statement is used inside the inner loop, only the inner loop will be skipped and the program will continue executing statements after the inner loop
- And, when the break statement is used in the outer loop, both the outer and inner loops will be skipped and the program will continue executing statements immediate to the outer loop.
Example
The following program demonstrates the use of break in afor loopiterating over alist. 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 followingoutputβ
number found in list