8. Illustrate the use of break and continue with example.

1. break Statement

The break statement is used to exit the loop immediately, even if the loop condition is still True.

Example:

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output:

Explanation:
The loop runs from 1 to 9, but when i becomes 5, the break statement stops the loop.

2. continue Statement

The continue statement skips the current iteration and moves to the next one.

Example:

Explanation:
When i is 3, the continue statement skips that iteration, so 3 is not printed.

Key Differences

Featurebreakcontinue
FunctionExits the loop completelySkips the current iteration only
UsageWhen you want to stop a loopWhen you want to skip a particular case

Leave a Reply

Your email address will not be published. Required fields are marked *