Python break, continue and pass


break, continue, and pass Statements in Python

These three statements are used to control the flow of loops in Python. Each one behaves differently and can be used in for and while loops.


1. break Statement

The break statement is used to terminate a loop prematurely. When the break statement is executed, the loop stops immediately, and the program continues with the next statement after the loop.

Example 1: break in a for Loop

for i in range(5): if i == 3: break # Exit the loop when i equals 3 print(i)

Output:

0 1 2

In this example, the loop is terminated when i equals 3, so the loop doesn't print 3 or continue further.

Example 2: break in a while Loop

i = 1 while i <= 5: if i == 4: break # Exit the loop when i equals 4 print(i) i += 1

Output:

1 2 3

Here, the loop terminates when i equals 4, and the loop doesn't print 4 or continue further.


2. continue Statement

The continue statement is used to skip the current iteration of the loop and move on to the next iteration. It doesn't terminate the loop; it just bypasses the remaining code for the current iteration.

Example 1: continue in a for Loop

for i in range(5): if i == 2: continue # Skip the iteration when i equals 2 print(i)

Output:

0 1 3 4

In this example, the loop skips the iteration when i equals 2, so 2 is not printed, but the loop continues with the next iteration.

Example 2: continue in a while Loop

i = 0 while i < 5: i += 1 if i == 3: continue # Skip the iteration when i equals 3 print(i)

Output:

1 2 4 5

Here, the loop skips the iteration when i equals 3, so 3 is not printed, but the loop continues with the next iteration.


3. pass Statement

The pass statement is a null operation; it does nothing when executed. It's used as a placeholder in situations where code is syntactically required but you don't want to execute any code at that point. It's often used during development when you're working on the structure of your code and haven't implemented certain parts yet.

Example 1: Using pass in a Loop

for i in range(5): if i == 2: pass # Do nothing when i equals 2 print(i)

Output:

0 1 2 3 4

Here, the pass statement is used when i == 2, but it has no effect. The loop continues normally, and 2 is still printed.

Example 2: pass in a Function

def my_function(): pass # Placeholder for future implementation

In this case, the pass statement is used as a placeholder. The function does nothing when called, but it prevents syntax errors while the rest of the program is being developed.


Summary of break, continue, and pass

  • break: Exits the loop entirely and moves to the next statement after the loop.
  • continue: Skips the current iteration and moves to the next iteration of the loop.
  • pass: Does nothing and is used as a placeholder where code is required syntactically.

These statements are useful for controlling the flow of loops and ensuring that your code behaves as expected based on specific conditions.