Control Statements
Control statements are used to change the execution flow inside loops. These include:
breakcontinuepass
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 statementsExample: Stop a loop when a condition is met
for i in range(1, 10):
if i == 5:
break
print(i)Output:
1
2
3
42. 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 trueExample: Skip a number
for i in range(1, 6):
if i == 3:
continue
print(i)Output:
1
2
4
53. 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:
passExample:
for i in range(3):
pass # used when block is needed but no action is requiredUsed 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
3Explanation:
2is skipped usingcontinue4stops 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