The continue
statement is helpful for skipping items without writing deeply-nested if
statements. The effect of executing a continue
statement is to skip the rest of the loop's suite. In a for
loop, this means that the next item will be taken from the source iterable. In a while
loop, this must be used carefully to avoid an otherwise infinite iteration.
We might see file processing that looks like this:
for line in some_file: clean = line.strip() if len(clean) == 0: continue data, _, _ = clean.partition("#") data = data.rstrip() if len(data) == 0: continue process(data)
In this loop, we're relying on the way files act like sequences of individual lines. For each line in the file, we've stripped whitespace from the input line, and assigned the resulting string to the clean
variable. If the length of this string is zero, the line was entirely whitespace, and we'll continue the loop with the next line. The continue
statement...