Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Loops Module 2 - Control Flow Python Python Basics Python Programming: From Zero to Real-World Applications

break and continue - Controlling Loop Flow

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • What break and continue do
  • When to use each
  • The pass statement
Terminalpython
# break: exit the loop entirely
for num in range(1, 10):
    if num == 5:
        break
    print(num)
# 1 2 3 4

# continue: skip this iteration, go to next
for num in range(1, 6):
    if num == 3:
        continue
    print(num)
# 1 2 4 5

Practical Example: Find First Even Number

Terminalpython
numbers = [1, 3, 5, 7, 8, 9, 10]
for num in numbers:
    if num % 2 == 0:
        print(f"Found even: {num}")
        break
# Found even: 8

Practical Example: Skip Odd Numbers

Terminalpython
for num in range(1, 11):
    if num % 2 != 0:
        continue   # skip odd numbers
    print(num)
# 2 4 6 8 10
The pass statement
pass does nothing. It is a placeholder for code you have not written yet. Useful for empty functions or classes.

Practical Exercise

Use break to find the first number divisible by 7 in range(1, 100)
Use continue to print only odd numbers from 1 to 20
Create an empty function with pass: def todo(): pass

Key Takeaways

  • break: exits the loop immediately.
  • continue: skips the rest of this iteration, goes to next.
  • pass: does nothing - placeholder for empty blocks.
  • break is for finding/exiting. continue is for filtering.
  • Avoid overusing break/continue - can make code hard to read.
Previously: Lesson 12 covered while loops.
Today: You learned: Control loop execution with break and continue.
Next: Lesson 14 covers range and enumerate.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments