Python

In Python, Loop Control Statements like break, continue, and pass change the execution of a loop from its normal sequence. These are essential for handling exceptions, optimizing performance, and creating placeholders during development.

1. The break Statement

The break statement is used to terminate the loop entirely. When Python encounters break, it immediately exits the loop and moves to the next line of code outside the loop.

  • Theory: Use this when a specific condition is met and you no longer need to continue the iterations (e.g., searching for an item in a list).

  • Loop Impact: It stops both for and while loops and skips the else block if one is present.

Python
# Searching for a number
numbers = [1, 5, 8, 12, 15, 20]

for n in numbers:
    if n == 12:
        print(f"Found {n}! Stopping search.")
        break  # Exit the loop immediately
    print(f"Checking: {n}")

2. The continue Statement

The continue statement skips the current iteration and moves to the next one in the sequence.

  • Theory: Use this when you want to "skip" a specific item but keep the loop running for the rest of the items.

  • Loop Impact: It returns to the top of the loop to evaluate the next item or condition.

Python
# Printing only odd numbers
for i in range(1, 6):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(f"Odd number: {i}")

3. The pass Statement

The pass statement is a null operation; nothing happens when it executes.

  • Theory: In Python, syntactically, a code block (like an if or a loop) cannot be empty. If you are planning to write code later but want the program to run now without errors, you use pass.

  • Loop Impact: It acts as a placeholder and does not affect the loop's execution.

Python
# Placeholder for future logic
for i in range(5):
    if i == 3:
        pass  # TODO: Handle this specific case later
    else:
        print(i)

Summary Table

StatementActionUse Case
breakStops the loop completely.When you find what you need or hit an error.
continueSkips the current turn.When you want to filter out certain values.
passDoes nothing.When you need an empty block for future code.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now