English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python break and continue

In this article, you will learn how to use break and continue statements to change the flow of loops.

What is the role of break and continue in Python?

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.

Python break statement

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.

Syntax of break

break

Break flowchart

Flowchart of the break statement in Python

for loopandwhile loopThe working of the break statement is as follows.

How does the break statement work

Example: Python break statement

#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.

Python continue statement

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.

Syntax of continue

continue

Continue flowchart 

Flowchart of the continue statement in Python

The working of the continue statement in for and while loops is as follows.

How does the continue statement work in Python

Example: Python continue

#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.