English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to use break and continue statements to change the flow of loops.
In Python, the break and continue statements can change the flow of a regular loop.
Loops traverse code blocks until the test expression is false, but sometimes we want to terminate the current iteration even the entire loop without checking the test expression. In these cases, the break and continue statements can be used.
The break statement terminates the loop that contains it. Program control is passed immediately to the statement after the loop body.
If the break statement is inside a nested loop (a loop within another loop), then the break statement will terminate the innermost loop.
break
for loopandwhile loopThe working of the break statement is as follows.
#Use break statement in loop for val in "string": if val == "i": break print(val) print("End")
Output result
s t r End
In this program, we traverse the 'string' sequence. We check if the letter is i so that we can exit the loop. Therefore, in the output, we see all the letters printed out until I print them. After that, the loop terminates.
The continue statement is used only to skip the rest of the code in the current iteration of the loop. The loop will not terminate but will continue to the next iteration.
continue
The working of the continue statement in for and while loops is as follows.
#This program shows the use of the continue statement within a loop for val in "string": if val == "i": continue print(val) print("End")
Output result
s t r n g End
This program is the same as the example above, but the break statement is replaced with continue. We continue the loop, and if the string is i, the rest of the block is not executed. Therefore, in the output, we see that all letters except i are printed out.