Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • distinguish break, continue, and pass
  • predict output in loop-control MCQs
  • avoid infinite loops with continue

break

  • exits the nearest loop immediately
for i in range(1, 10):
    if i == 5:
        break
    print(i)
Output: 1 2 3 4

continue

  • skips current iteration remainder
  • moves to next iteration
for i in range(1, 8):
    if i % 2 == 0:
        continue
    print(i)
Output: 1 3 5 7

pass

  • does nothing (placeholder)
  • keeps syntax block valid
for i in range(3):
    if i == 1:
        pass
    print(i)
Output: 0 1 2

Side-by-side meaning

KeywordEffect
breakterminate loop
continueskip to next iteration
passno operation

Nested loop nuance with break

for i in range(3):
    for j in range(5):
        if j == 2:
            break
        print(i, j)
break affects inner loop only.

Infinite-loop trap with while + continue

i = 0
while i < 5:
    if i == 2:
        continue
    i += 1
Stuck at i == 2 forever because update is skipped. Safe version:
i = 0
while i < 5:
    i += 1
    if i == 2:
        continue
    print(i)

Exam hints and traps

  • pass does not skip loop like continue
  • break exits loop; code after loop still runs
  • in nested loops, identify which loop each statement controls

Practice

  1. Print numbers 1 to 20, stop at first multiple of 7.
  2. Print all numbers 1 to 10 except 4 and 8.
  3. Use pass inside unfinished if block example.

Sample snippets

for i in range(1, 21):
    if i % 7 == 0:
        break
    print(i)
for i in range(1, 11):
    if i in (4, 8):
        continue
    print(i)