break, continue, pass, and else work the SAME way with for as they do with while.
breakβ stop theforloop immediately (no more iterations).elseβ runs only when theforloop finishes normally (nobreak).passβ do nothing (placeholder when loop body must have a statement).continueβ skip the rest of this iteration, go to the next.
Letβs go! π
Part 1: break WITH for
π break exits the for loop immediately. Same as with while.
for i in range(10):
if i > 5:
break
print(i)
i takes 0, 1, 2, 3, 4, 5, 6, ... When i is 6, i > 5 is True β break. So we print 0, 1, 2, 3, 4, 5 only.
Demo:
for i in range(10):
if i > 5:
break
print(f" {i}", end=" ")
print(" β loop ended (break)")
Part 2: else WITH for
π You can attach else to a for loop. The else block runs ONLY when the loop completes without hitting break (all iterations finished). If we break out, else does NOT run.
Demo 1: No break β else runs
for i in range(3):
print(f" {i}", end=" ")
else:
print("\n [else] For completed properly.")
Demo 2: With break when i==2 β else does NOT run
for i in range(5):
if i > 2:
break
print(f" {i}", end=" ")
else:
print("\n [else] This will not print.")
Part 3: pass WITH for
π In Python the body of a for loop cannot be empty. If you have nothing to do, use pass.
for i in range(5):
pass
print("Program ended.")
The loop runs 5 times but does nothing; then "Program ended." is printed.
Demo:
for i in range(3):
pass
print(" Program ended.")
Part 4: continue WITH for
π continue skips the rest of the current iteration and goes to the next. Same as with while.
for i in range(10):
if i % 5 == 0:
continue
print(i)
When i is 0 or 5, i % 5 == 0 is True β continue, so we skip print. We print: 1,2,3,4,6,7,8,9 (0 and 5 are skipped).
Demo: print i except when i % 5 == 0 (skip 0 and 5)
for i in range(10):
if i % 5 == 0:
continue
print(f" {i}", end=" ")
print(" β 0 and 5 skipped")
Part 5: Summary
β
break β stop the loop (for or while). Else block does not run.
β
else β with for/while: runs only when loop ends normally (no break).
β
pass β do nothing. Use when a block must have a statement.
β
continue β skip rest of this iteration; next iteration still runs.
Same behavior in for and while. Remember: "loop completed without break" β else runs.
Congratulations! You now understand break, continue, pass, and else with for loops in Python! π
Key Takeaways:
breakstops the loop completelyelseruns only on normal completioncontinueskips just the current iterationpassis the "do nothing" placeholder
Next Steps:
- Combine
break+elseto search for a value ("found" vs "not found") - Use
continueto skip unwanted values in lists or strings - Practice with real problems (prime check, factorial with early stop, etc.)