Lesson 08
break Statement — Exit a Loop Early
Use Python break inside for and while loops to terminate iteration early. Learn how break skips the loop else block and see string search examples.
Beginner25 min
Transfer flow statements
The purpose of transfer flow statements is to transfer control of PVM from one part of the program to another.
Python has 4 types:
breakcontinuepassreturn(in functions — see Functions module)
This lesson covers break.
break statement
breakis a keyword.breakmust be used inside loops — otherwiseSyntaxError.- Purpose: terminate loop execution logically when a condition is satisfied; PVM exits the loop and runs other statements in the program.
- When
breakruns insidefororwhile, the correspondingelseblock is NOT executed (the loop did not end by condition becoming false).
Syntax — break in for loop
for varname in iterable_object:
if test_cond:
break
# other statementsSyntax — break in while loop
while test_cond_1:
if test_cond_2:
break
# other statementsExample 1 — for loop with and without break
s = "PYTHON"
print("for loop without break")
for ch in s:
print(ch)
else:
print("for loop --else part")
print("for loop with break kwd")
for ch in s:
if ch == "O":
break
else:
print(ch, end="")
else:
print("for loop --else part")
print("\nOther Part of the Program")Example 2 — break in while loop
s = "PYTHON"
i = 0
while i < len(s):
if s[i] == "H":
break
else:
print(s[i], end="")
i = i + 1
else:
print("while loop --else part")
print("\nOther statements in program")Example 3 — Stop after second 'I'
s = "MISSISSIPPI"
ictr = 0
for ch in s:
if ch == "I":
ictr = ictr + 1
if ictr == 2:
break
else:
print(ch, end="")
else:
print(ch, end="")break vs continue vs pass
| Keyword | Effect |
|---|---|
break |
Exit loop completely |
continue |
Skip rest of current iteration |
pass |
Do nothing — placeholder |
Loading playground…