3.4 break, continue, pass
Understanding the special commands break, continue, and pass for detailed flow control within loops, allowing for early termination, skipping iterations, or using placeholders.
The break Statement
The `break` statement is used to immediately terminate the current loop (either `for` or `while`). Once `break` is encountered, program execution transfers to the first statement after the loop. It is useful when we have found what we are looking for and do not need to continue the remaining iterations.
# Example of break in a for loop
print("Searching for the number 5:")
for i in range(10):
if i == 5:
print("Found 5, breaking the loop.")
break # Immediate exit from the loop
print(f"Checking number: {i}")
print("We have exited the loop.")
The continue Statement
The `continue` statement is used to interrupt the current iteration of the loop and immediately move to the next iteration. The code following `continue` within the loop body is skipped for the current iteration. It is useful when we want to ignore specific values and continue with the next ones.
# Example of continue
print("\nPrinting only odd numbers from 0 to 9:")
for i in range(10):
# If the number is even...
if i % 2 == 0:
continue # ...skip this iteration and go to the next one
# This line is executed only for odd numbers
print(f"Odd number: {i}")
The pass Statement
The `pass` statement is a command that does absolutely nothing. It acts as a placeholder. It is used when Python's syntax requires a code block (e.g., after `if`, `for`, `def`), but you do not want to write any commands yet. It allows you to maintain the program structure without causing an `IndentationError`, with the intention of adding the logic later.
# Example of pass
def my_function_todo():
# TODO: I will implement this function tomorrow
pass # The function does nothing, but the syntax is correct
# A loop that does nothing yet
for i in range(5):
pass # No action is performed
print("\nThe program continues normally after the blocks with 'pass'.")
Practical Exercises
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.