Python break, continue, and pass Statements

These keywords control the flow of loops in Python.

`break` Statement

The break statement terminates the loop prematurely, regardless of whether the loop condition is still true.


for i in range(1, 11):
  if i == 5:
    break  # Exit the loop when i is 5
  print(i)
    

Output:


1
2
3
4
    

`continue` Statement

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


for i in range(1, 11):
  if i == 5:
    continue  # Skip printing 5
  print(i)
    

Output:


1
2
3
4
6
7
8
9
10
    

`pass` Statement

The pass statement does nothing. It's used as a placeholder when a statement is syntactically required but no code needs to be executed.


for i in range(1, 11):
  if i == 5:
    pass  # Do nothing when i is 5 (no action)
  else:
     print(i)
    

Output:


1
2
3
4
6
7
8
9
10
    

Example with `while` loop and `break`


i = 1
while i <= 10:
  if i == 7:
    break
  print(i)
  i += 1
    

Output:


1
2
3
4
5
6
    

Example with nested loops and `break`


for i in range(1, 4):
  for j in range(1, 4):
    if i == 2 and j == 2:
      break
    print(f"({i}, {j})")
    

Output:


(1, 1)
(1, 2)
(1, 3)
(2, 1)
    

Important Considerations

Use break to exit loops immediately when a specific condition is met. Use `continue` to skip to the next iteration. Use `pass` as a placeholder when no action is needed in a block of code. Be mindful of the scope of these statements within your loops to ensure they affect only the intended parts of your program flow.