Break/Continue
In short: Two jump statements for deliberately changing the normal flow of a loop: break immediately ends the loop entirely, continue only skips the rest of the current iteration and moves on to the next one.
In more detail: break is used, for example, to abort a search as soon as the sought element is found, instead of unnecessarily iterating through the rest of the collection. continue is suitable for skipping certain elements without leaving the whole loop — e.g. to only process the even numbers in a list of numbers. Both also work in switch statements (there, break ends the respective case).
In Depth
# break: abort the search immediately once found
for number in list_:
if number == target:
print("Found!")
break # the rest of the list is no longer checked at all
# continue: only process even numbers, skip odd ones
for number in list_:
if number % 2 != 0:
continue # jump directly to the next loop iteration
process(number)The difference matters for avoiding infinite loops: for a while loop with continue, you have to make sure the condition variable is still updated before jumping to the next iteration — otherwise the loop keeps checking the same (never satisfied) exit condition and runs forever.
For nested loops (one loop inside another), break by default only aborts the innermost loop, not the outer one:
for i from 0 to 3:
for j from 0 to 3:
if (condition):
break // only ends the inner j loop
// outer i loop continues running normallySome languages offer “labeled” break statements for this, to deliberately leave an outer loop (break outer; with a previously set label outer:). Where that doesn’t exist, people usually help themselves with a helper variable (a “flag”) that’s also checked by the outer loop after the inner break, or they extract the nested logic into its own function and use a simple return there — often the more readable solution anyway.
Excessive use of break/continue is considered in some style traditions a sign of overly complex control flow — an alternative is often to integrate the exit condition directly into the loop condition itself, where that’s possible without nesting.
See also: Loops, Switch Statement