
Python
Two statements give you power to control exactly when loops stop or skip iterations.
`break` exits the loop immediately:
for i in range(10):
if i == 5:
break # Exits loop when i is 5
print(i)
# Output: 0, 1, 2, 3, 4Real example: Search and exit
for number in [1, 3, 5, 7, 9, 12]:
if number == 12:
print("Found even number!")
break
print(f"Checking {number}")`continue` skips the rest of the current iteration:
for i in range(5):
if i == 2:
continue # Skips to next iteration
print(i)
# Output: 0, 1, 3, 4Real example: Skip unwanted items
for number in [1, 2, 3, 4, 5]:
if number % 2 == 0:
continue # Skip even numbers
print(f"Odd: {number}")
# Output: Odd: 1, Odd: 3, Odd: 5Example 1: User menu with break
while True:
choice = input("Enter 'quit' to exit: ")
if choice == "quit":
break
print(f"You entered: {choice}")Example 2: Filtering data with continue
# Process only valid scores
scores = [95, -5, 87, 100, -10, 88]
for score in scores:
if score < 0:
continue # Skip invalid scores
print(f"Valid score: {score}")| Statement | Effect | Use When |
|---|---|---|
| `break` | Exit entire loop | Found what you need |
| `continue` | Skip to next iteration | Want to skip this item |
| Concept | Remember |
|---|---|
| break | Completely exits the loop |
| continue | Skips rest of iteration |
| Indentation | Both must be inside loop |
| Nesting | Only breaks/continues innermost loop |
Iterate through collections with Iterating Lists!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward