4.3 Control Statements: continue, assert, pass, return (BT101CO)

Beyond standard loops and conditions, Python provides specific keywords to control the flow of execution, handle errors, and return data from blocks of code.

1. continue and pass

These keywords are primarily used inside loops to control iteration behavior.

  • continue: Skips the rest of the code in the current iteration and jumps to the next one.
  • pass: A placeholder statement that does absolutely nothing. Use it when code is required syntactically (like inside an empty function or loop) but you aren't ready to implement logic.
# Example of pass
def future_function():
    pass  # To be implemented later

# Example of continue
for i in range(5):
    if i == 2:
        continue # Skips printing 2
    print(i, end=" ") # Output: 0 1 3 4

2. The assert Statement

The assert keyword is used for debugging. It checks if a condition is True. If the condition is False, it raises an AssertionError and stops the program.

# Syntax: assert condition, "Error Message"

age = -5
assert age >= 0, "Age cannot be negative!"
# Since -5 is not >=0, this will crash with an AssertionError

3. The return Statement

The return statement is used inside functions to send a value back to the caller. It exits the function immediately.

def add(a, b):
    return a + b

result = add(10, 20)
print(result) # Output: 30

Note: We will explore functions in depth in Unit 5.

Practice Quiz