3 3 Loop Control Statements Explained
Key Concepts
Loop control statements in Python allow you to alter the flow of loops. The key concepts include:
break
statementcontinue
statementpass
statement
1. The break
Statement
The break
statement is used to exit a loop prematurely. When encountered, the loop is terminated immediately, and the program continues with the next statement after the loop.
Example:
for i in range(10): if i == 5: break print(i)
Think of the break
statement as an emergency exit. If a certain condition is met, the loop stops, and the program moves on.
2. The continue
Statement
The continue
statement is used to skip the rest of the loop body for the current iteration and move to the next iteration. It does not terminate the loop but skips the remaining code in the loop body.
Example:
for i in range(10): if i % 2 == 0: continue print(i)
Think of the continue
statement as a way to skip a step in a recipe. If a certain ingredient is missing, you skip that step and move on to the next one.
3. The pass
Statement
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 as a placeholder for future code.
Example:
for i in range(5): if i == 3: pass print(i)
Think of the pass
statement as a placeholder for a future task. It allows you to keep the structure of your code intact while leaving a space for future implementation.
Putting It All Together
By understanding and using break
, continue
, and pass
statements, you can create more flexible and dynamic loops in your Python programs. These statements allow you to control the flow of your loops based on specific conditions, making your code more efficient and responsive.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum = 0 for num in numbers: if num == 3: continue if num == 8: break sum += num print("Sum of numbers (excluding 3 and stopping at 8):", sum)
This example demonstrates how to sum a list of numbers while skipping a specific value and stopping the loop at another specific value using continue
and break
statements.