The continue and break statements
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 ...
Get Python Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.