Break in Python

In Python, the break statement allows you to exit a loop immediately.

break

When the interpreter encounters a break statement, it transfers control to the first statement following the loop.

You can use the break statement in both for and while loops.

Note: The break statement exits the entire loop. To skip just one iteration of the loop, use the continue statement.

    Practical Examples

    Here are some practical examples of using the break statement in for and while loops.

    Example 1 (while loop)

    This while loop is designed to run for 6 iterations.

    However, at the third iteration, the break statement forces an exit from the loop.

    1. x = 0
    2. while x < 6:
    3. x += 1
    4. if x == 3: break
    5. print(x)
    6. print("end")

    The output of the script is:

    1
    2
    end

    The break statement is particularly useful in while loops to avoid infinite loops.

    Example 2 (for loop)

    This for loop is set to run for 5 iterations.

    However, at the third iteration, the break statement causes an early exit from the loop.

    1. for i in range(1, 5):
    2. if i == 3: break
    3. print(i)

    The output of the script is:

    1
    2

    And so on.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Loop Structures in Python

    Forced Interruptions and clauses