Python Continue and Break Statements

Python Continue and Break Statements

The break and continue statements in Python are control flow statements used to alter the execution of loops (for or while). These statements give programmers finer control over how loops execute. Below is an explanation of each statement, along with its syntax and examples.


break Statement

The break statement is used to exit a loop prematurely. When executed, it immediately terminates the loop, and the program continues with the first statement following the loop.

Syntax

  break

Usage Example

Example: Using break in a for loop

  # Example: Using break in a for loop
  for number in range(1, 10):
      if number == 5:
          print("Breaking the loop at number", number)
          break  # Exit the loop when number equals 5
      print(number)

  # Output:
  # 1
  # 2
  # 3
  # 4
  # Breaking the loop at number 5

Example: Using break in a while loop

  # Example: Using break in a while loop
  count = 0
  while count < 10:
      if count == 6:
          print("Breaking the loop at count", count)
          break
      print(count)
      count += 1

  # Output:
  # 0
  # 1
  # 2
  # 3
  # 4
  # 5
  # Breaking the loop at count 6

continue Statement

The continue statement is used to skip the current iteration of the loop and proceed to the next iteration. The loop does not terminate; only the statements after continue within the loop are skipped for the current iteration.

Syntax

  continue

Example: Using break in a for loop

  # Example: Using continue in a for loop
  for number in range(1, 10):
      if number % 2 == 0:  # Skip even numbers
          continue  # Skip the rest of the loop for even numbers
      print(number)

  # Output:
  # 1
  # 3
  # 5
  # 7
  # 9

Example: Using continue in a while loop

  # Example: Using continue in a while loop
  count = 0
  while count < 10:
      count += 1
      if count % 2 == 0:  # Skip even numbers
          continue
      print(count)

  # Output:
  # 1
  # 3
  # 5
  # 7
  # 9

Key Differences Between break and continue

Aspect break continue
Effect on Loop Terminates the loop entirely. Skips the rest of the current iteration.
Control Flow Exits the loop immediately. Proceeds to the next iteration.
Scope of Action Ends the loop execution. Skips statements after continue in the current iteration.

Summary

  • Use break when you need to exit a loop before its natural termination condition is met.
  • Use continue when you need to skip specific iterations of the loop but want the loop to continue running.

These statements are particularly useful in scenarios such as filtering data, breaking out of nested loops, or handling specific conditions dynamically.

Previous Next