DEV Community

Max
Max

Posted on • Edited on

Python break and continue tutorial

In Python break and continue are two keywords used for flow control in loops. break is used to exit out of a loop, while continue is used to skip an iteration and move on to the next one. In this tutorial, we'll go over how to use break and continue in different types of loops in Python.

Using break in loops

break is used to exit out of a loop. When break is encountered in a loop, the program exits out of the loop and continues executing the code after the loop. Here's an example of how to use break in a for loop:

fruits = ["One", "Two", "Three", "Four", "Five"]
for fruit in fruits:
    if fruit == "Three":
        break
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

Output:

One
Two
Enter fullscreen mode Exit fullscreen mode

Using continue in loops

continue is used to skip an iteration and move on to the next one. When continue is encountered in a loop, the program skips the remaining code in the current iteration and moves on to the next one. Here's an example of how to use continue in a while loop:

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
4
5
Enter fullscreen mode Exit fullscreen mode

In this example, the number 3 is skipped because of the continue statement.

Explore Other Related Articles

Python While Loop tutorial
Python For Loops, Range, Enumerate Tutorial
Python if-else Statements Tutorial
Python set tutorial
Python tuple tutorial

Top comments (0)