Python provides special control statements like break, continue, and pass to alter the flow of loops or to handle cases where no action is required. This article explains these statements with examples.
The break statement is used to exit a loop prematurely when a specific condition is met. It is commonly used when the required task is complete, and there is no need to continue looping.
The following example stops the loop when the number 3 is encountered:
# Example of break statement for num in range(1, 6): if num == 3: break print(num)
Output:
1 2
The continue statement is used to skip the current iteration and move to the next iteration of the loop. It is helpful when certain cases need to be ignored during looping.
The following example skips the number 3 and continues with the rest of the loop:
# Example of continue statement for num in range(1, 6): if num == 3: continue print(num)
Output:
1 2 4 5
The pass statement is a placeholder that does nothing. It is used when a statement is syntactically required but no action is needed. It is often used during code development to indicate sections of the code to be implemented later.
The following example demonstrates the pass statement in a loop:
# Example of pass statement for num in range(1, 6): if num == 3: pass # Placeholder for future code print(num)
Output:
1 2 3 4 5
Here is a summary of the differences between these statements:
The break, continue, and pass statements provide greater control over loops and program execution. Understanding their behavior is essential for writing efficient and readable code.