Python Docs

Break / Continue

Loop Control Statements: break and continue :

In Python loops (both for and while), sometimes you want to change the natural flow of the loop. Two special statements are used for that:

1. break Statement :

Theory :

The break statement immediately stops the loop.

It ends the loop even if the loop condition is still true.

Code after the loop continues executing normally.

When to Use :

  • When a condition is met
  • When searching and the target is found
  • To prevent infinite loops

Example

i = 1
while i <= 10:
    print(i)
    if i == 5:
        break  # Stop the loop when i becomes 5
    i += 1

Output:

1 2 3 4 5

Even though the condition allowed the loop to continue until 10, the break forced an early exit.

2. continue Statement

Theory :

The continue statement skips the current iteration of the loop.

It does not stop the loop.

The loop moves directly to the next iteration.

When to Use :

Use continue when:

  • You want to ignore specific values
  • You want to skip processing certain cases
  • You want to avoid writing nested if statements

Example

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue  # skip printing number 3
    print(i)

Output:

1 2 4 5

The loop skipped printing the value 3, but continued running.

Both Together:

Example

i = 0

while i < 10:
    i += 1

    if i == 3:
        continue  # skip 3

    if i == 8:
        break  # stop at 8

    print(i)

Output:

1 2 4 5 6 7

3 was skipped

Loop ended when i reached 8

  • break → Ends loop immediately
  • continue → Skips one iteration, but loop continues