Control Flow with break and continue

In Python, break and continue are control flow statements that allow you to modify the normal execution of loops.

1. The break Statement:

The break statement is used to exit a loop prematurely. When encountered, the loop immediately terminates, and the program continues with the next statement after the loop.

# Example of the break statement in a while loop
i = 0

while i < 10:
    i += 1

    if i == 5:
        break  # Exit the loop when i is 5


2. The continue Statement:

The continue statement is used to skip the rest of the code in the current iteration and move to the next iteration of the loop.

# Example of the continue statement in a for loop
for i in range(10):
    if i % 2 == 0:
        continue  # Skip the rest of the code in this iteration for even numbers


3. Using break and continue in Nested Loops:

You can use break and continue in nested loops to control the flow at different levels.

# Example of break and continue in nested loops
for i in range(5):
    for j in range(5):
        if i == 2 and j == 3:
            break  # Exit both loops when i is 2 and j is 3

        if j == 1:
            continue  # Skip the rest of the code in this iteration for j equals 1

        print(f"({i}, {j})")

4. Looping with else and break:

You can use the else clause with a loop to execute a block of code when the loop completes without encountering a break statement.

# Example of using else with break in a while loop
i = 0

while i < 5:
    i += 1

    if i == 3:
    print("Loop finished without a break statement.")

5. Conclusion:

break and continue are powerful tools for controlling the flow of loops in Python. Whether you need to exit a loop prematurely or skip specific iterations, these statements provide flexibility in handling different scenarios.

Understanding when and how to use break and continue can significantly improve the efficiency and clarity of your code, especially in situations where you need to navigate through complex data or handle specific conditions.

In the next sections, we’ll explore more advanced topics and practical applications of control flow in Python.