Flow Control Basics in Python
Loops are the backbone of programming. They let you run repetitive code until a certain condition is met. However, during execution, you often need to exit a loop early, skip a specific iteration, or simply leave a block empty for future implementation.
Python provides three special flow control operators. Each one solves a specific problem when working with loops and conditional statements.
How Loops Behave Without Control Statements
Before diving into control statements, it's important to understand the default behavior of loops. By default, a loop runs through all iterations from start to finish:
for i in range(5):
print(i)
Output:
0
1
2
3
4
A standard for loop processes every element in a sequence. To change this behavior, you use special operators.
The break Statement: Exiting a Loop Early
How break Works
The break statement immediately terminates the nearest loop it's inside. This applies to both for loops and while loops.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
As soon as the variable i reaches 5, the loop stops completely. The remaining iterations are skipped.
Practical Uses for break
The break statement is widely used in these scenarios:
- Early exit when a condition is met
- Breaking out of potentially infinite loops
- Finding the first matching element in a sequence
- Handling critical errors inside loops
Finding the First Divisor of a Number
n = 17
for i in range(2, n):
if n % i == 0:
print(f"First divisor: {i}")
break
else:
print("Prime number")
Key insight: if the loop finishes naturally without hitting break, the else block runs. This lets you distinguish between the two ways a loop can end.
The continue Statement: Skipping to the Next Iteration
How continue Works
The continue statement skips the remaining code in the current iteration and jumps to the next step of the loop. The loop keeps running, but certain values are handled differently.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
The value 2 is completely skipped because the continue statement triggers when i == 2.
Common Uses for continue
Continue is often used for:
- Filtering out unwanted values
- Skipping lines when processing files
- Implementing data validation conditions
- Creating filters in parsers and handlers
Filtering Even Numbers
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output:
1
3
5
7
9
All even numbers are skipped, and only odd values are printed.
The pass Statement: Doing Nothing
Purpose of pass
The pass statement is a no-op. It doesn't perform any action, but it's syntactically required in places where Python expects a statement.
for i in range(5):
if i == 3:
pass
print(i)
Output:
0
1
2
3
4
The pass statement executes when i == 3, but it doesn't affect the program's flow.