Control Statements
Control statements are used to change the execution flow inside loops. These include:
break
continue
pass
They are most commonly used within for
and while
loops.
1. break
Statement
The break
statement is used to exit the loop prematurely, regardless of the loop’s condition.
Syntax:
for item in iterable:
if condition:
break
# other statements
Example: Stop a loop when a condition is met
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
2. continue
Statement
The continue
statement skips the current iteration and moves to the next one.
Syntax:
for item in iterable:
if condition:
continue
# this code is skipped if condition is true
Example: Skip a number
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
3. pass
Statement
The pass
statement does nothing. It's used as a placeholder when a statement is syntactically required but you don’t want any code to run.
Syntax:
for item in iterable:
pass
Example:
for i in range(3):
pass # used when block is needed but no action is required
Used commonly during development to prevent errors in empty blocks.
Summary Table
Statement | Description | Use Case |
---|---|---|
break | Exit the loop early | Stop a loop when a condition is met |
continue | Skip current loop iteration | Skip processing specific values |
pass | Do nothing (placeholder) | Write code later, maintain valid syntax |
Combined Example
for i in range(1, 6):
if i == 2:
continue
elif i == 4:
break
else:
print(i)
Output:
1
3
Explanation:
2
is skipped usingcontinue
4
stops the loop withbreak
Practice Exercise
Task: Print numbers from 1 to 10, but skip 5 and stop if 8 is reached.
for i in range(1, 11):
if i == 5:
continue
if i == 8:
break
print(i)
Output:
1
2
3
4
6
7