Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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:

  1. break
  2. continue
  3. pass
  4. return (in functions — see Functions module)

This lesson covers break.

break statement

  • break is a keyword.
  • break must be used inside loops — otherwise SyntaxError.
  • Purpose: terminate loop execution logically when a condition is satisfied; PVM exits the loop and runs other statements in the program.
  • When break runs inside for or while, the corresponding else block is NOT executed (the loop did not end by condition becoming false).

Syntax — break in for loop

python
for varname in iterable_object:
    if test_cond:
        break
    # other statements

Syntax — break in while loop

python
while test_cond_1:
    if test_cond_2:
        break
    # other statements

Example 1 — for loop with and without break

python
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

python
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'

python
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

Next: File 09 — continue Statement

Loading playground…