Part 03 / Topic 8 of 12
break, continue, pass
| Keyword | What it does |
|---|---|
break |
stop the loop right now |
continue |
skip the rest of this round, go to the next item |
pass |
do nothing (a placeholder so the code is valid) |
break and continue only affect the innermost loop they are in.
Real-world example: scan parcels: skip damaged ones, stop at the first parcel for Pune.
parcels = ["Delhi", "damaged", "Mumbai", "Pune", "Chennai"]
for city in parcels:
if city == "damaged":
continue # skip this one
if city == "Pune":
print("Found Pune parcel, stopping.")
break # stop the loop
print(f"Deliver to {city}")
# Deliver to Delhi
# Deliver to Mumbai
# Found Pune parcel, stopping.
for n in range(3):
pass # TODO: write this later
Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.