break, continue, and Loop else
Unit ID: M04-U05 Estimated active time: 22-30 minutes
Stop a search with break
course_codes = ["AI-01", "PY-01", "ML-01"]
target = "PY-01"
found = False
for code in course_codes:
if code == target:
found = True
break
print(found)
break exits the nearest loop immediately. Use it when continuing cannot improve the result, such as after finding the first required match.
Skip one iteration with continue
hours = [8, -2, 12]
valid_total = 0
for value in hours:
if value < 0:
continue
valid_total = valid_total + value
continue skips the remaining block for the current item and moves to the next item. Record rejected data before continuing if it must remain auditable.
Loop else means no break
for code in course_codes:
if code == "DATA-01":
print("Found")
break
else:
print("Not found")
The else block runs when the loop finishes normally without break. It does not mean "after every loop".
Use loop else only when it makes the search clearer. A flag can be more familiar for beginners.
Keep rejected evidence
accepted = []
rejected = []
for value in [8, -2, 12]:
if value < 0:
rejected.append({"value": value, "reason": "below zero"})
continue
accepted.append(value)
Nothing disappears silently.
Practice
Search codes = ["M01", "M02", "M03"] for "M04". Implement once with a flag and once with loop else. Then process [4, None, 6], recording None as rejected before using continue.
Takeaway
break ends a loop, continue skips one iteration, and loop else runs when no break occurred. Control statements should make the reason clearer, not merely shorten code. Next, we will name the state built during a loop.
