Python looping control (break + continue + pass)

by-passing a loop depending on exceptions
2025-11-04 15:56
// updated 2025-11-04 16:25

In Python, the following three keywords allow us to by-pass a loop, depending on special cases:

  • break (skip out of the loop entirely)
  • continue (perform no action and go to the next iteration)
  • pass (perform no action but finish the iteration)

break statement

This statement seems the most straightforward out of the three: just "break" out of the loop entirely:

names = ['Alice', 'Bob', 'Carl', 'Dan', 'Eve']
 
for name in names:
  if 'r' in name.lower():      
      break
      print('(name redacted)')
  else:
      print(name)

# Output:
# Alice
# Bob

In the example above, we break out of the loop because Carl's name has an "r" in it; the loop will stop and no further execution of it will happen!

continue statement

This statement might get confused with the pass statement (explained further below) so we will need to remember that a continue statement continues the loop and not the block:

names = ['Alice', 'Bob', 'Carl', 'Dan', 'Eve']
 
for name in names:
  if 'r' in name.lower():      
      continue
      print('(name redacted)')
  else:
      print(name)

# Output:
# Alice
# Bob
# Dan
# Eve

Note how the statement printing "(name redacted)" inside the if block does not execute!

pass statement

This statement will pass through the block, executing any remaining code:

names = ['Alice', 'Bob', 'Carl', 'Dan', 'Eve']
 
for name in names:
  if 'r' in name.lower():      
      pass 
      print('(name redacted)')
  else:
      print(name)

# Output:
# Alice
# Bob
# (name redacted)
# Dan
# Eve

The names continue and pass might indeed sound confusing an this does this a lot of practice to differentiate the nuances between them! An easy way to remember them is to think about the loop and not the iteration when using the words!

⬅️ older (in textbook-python)
🐍 Python looping (for + while)
newer (in textbook-python) ➡️
Python error handling (try + except + finally) 🐍
⬅️ older (in code)
🐍 Python looping (for + while)
⬅️ older (posts)
🐍 Python looping (for + while)