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 5Practical 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: 8Practical 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 10The 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.
Comments
Comments
Post a Comment