[Python][C][C++][For noobs] What is 'continue'

'continue' statement is like a 'goto' to the end of loop body.

For example, you want to enumerate all tripes of numbers in range 1..5, but if a number doesn't repeat in triple. First version:

#!/usr/bin/env python3

for i in range(5):
    for j in range(5):
        for k in range(5):
            if i!=j:
                if j!=k:
                    if i!=k:
                        print (i, j, k)

Not good. Spaghetti code in worst sense. Better:

#!/usr/bin/env python3

for i in range(5):
    for j in range(5):
        for k in range(5):
            if i!=j and j!=k and i!=k:
                print (i, j, k)

Still not good. Even better:

#!/usr/bin/env python3

for i in range(5):
    for j in range(5):
        for k in range(5):
            if i==j:
                continue # read it as 'skip loop body'
            if j==k:
                continue # read it as 'skip loop body'
            if i==k:
                continue # read it as 'skip loop body'
            print (i, j, k)

Now this is real code from my practice. I parse WET files from commoncrawl DB using warcio. Picking only 'coversion' records with English language.

#!/usr/bin/env python3

from warcio.archiveiterator import ArchiveIterator
import sys

with open(sys.argv[1], 'rb') as stream:
    for record in ArchiveIterator(stream):
        if record.rec_type=='conversion':
            h=record.rec_headers
            lang=h['WARC-Identified-Content-Language']
            if lang=='eng':
                print (h)

Isn't this better?

#!/usr/bin/env python3

from warcio.archiveiterator import ArchiveIterator
import sys

with open(sys.argv[1], 'rb') as stream:
    for record in ArchiveIterator(stream):
        if record.rec_type!='conversion':
             continue
        h=record.rec_headers
        lang=h['WARC-Identified-Content-Language']
        if lang!='eng':
            continue
        print (h)

Many PLs with Algol-derived syntax has the 'continue' statement.

(the post first published at 20230129.)


List of my other blog posts.

Subscribe to my news feed

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.