Python break and continue



What does continue and break do in Python?

In Python, break and continue statements can modify the normal flow of a loop.

Loops iterate over a portion of code until the condition is false. But in some cases, you need to terminate the current iteration or exit a loop without checking the condition. In these cases, the break and continue statements are used.


Python break statement

The break statement terminates the current loop and resumes to the next statement after the loop's body.

If the break statement is inside a nested loop, the break statement will terminate the innermost loop.


Syntax of break

The syntax for a break statement in Python is as follows:

break

Flowchart of break

The flowchart of the break statement is as follows:

Flowchart of break in Python

The working of break statement in for loop and while loop can be given as follows:

The working of break statement in Python

Python break - Example

In the following example, we will iterate through the fruits list. If the list contains the "mango" fruit, we will break from the loop.

fruits = ["kiwi", "grape", "mango", "raspberry"]

for fruit in fruits:
    if fruit == "mango":
    break
    print(fruit)

print("The end")

After running the above code, the output will be as follows:

kiwi
grape
The end

Python continue statement

The continue statement is used to skip the rest of the code inside a loop for just the current iteration. With the continue statement, loops do not terminate but continue to the next iteration.


Syntax of continue

The syntax for a continue statement in Python is as follows:

continue

Flowchart of continue

The flowchart of the continue statement is as follows:

Flowchart of continue statement in Python

The working of continue statement in for loop and while loop can be given as follows:

The working of continue statement in Python

Python continue - Example

In the following example, we will continue with the loop if the "fruits" list contains the "mango" item. So the "mango" item will not be printed.

fruits = ["kiwi", "grape", "mango", "raspberry"]

for fruit in fruits:
    if fruit == "mango":
    continue
    print(fruit)

print("The end")

After executing the above code, the output will be as follows:

kiwi
grape
raspberry
The end


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.