Continue—Python

The continue statement is used in Python to return program execution to the beginning of a loop. For a review of loops see for loops and while loops.

Let’s begin with a code example

names = ['Bob Belcher',
         'Linda Belcher',
         None,
         'Louise Belcher',
         'Tina Belcher',
         None,
         'Gene Belcher']

bob = ''
for name in names:
    if name is None:
        continue    # Go back to the top of the loop since
                    # since we can't do comparisons on None
    if 'Bob' in name:
        bob = name

In this situation, we have a list object that has a combination of Strings and Python’s None object. What we are doing is trying to find ‘Bob’ but to do that, we need a way to skip over the None objects or our program will crash. Lines 11 and 12 in the above code snippet do the job of checking if the elemnt name is None first. If it turns out that the element is None, line 12 uses the continue statement to return the execution to the top of the loop.

The continue keyword is useful when we process a loop of mixed types. Let’s take another example of where the keyword is also useful.

while True:
    fileName = input('Enter a file name => ')
    try:
        lines = open(fileName, 'r').readlines()
    except FileNotFoundError:
        print('Try a different file')
        continue # We can't do the next part because
                 # couldn't open the file
    for line in lines:
        print(line)

This code snippet asks the user for a file and then attempts to open the file for processing. However, if for some reason we can’t open the file, the program won’t be able to process lines 9 and 10. For this reason, we use the continue keyword to return program execution to the top of the loop and give the user an opportunity to open a different file.

One thought on “Continue—Python”

  1. You really make it seem so easy with your presentation but I find this topic to be really something that I think I would by no means understand. It sort of feels too complicated and extremely large for me. I’m looking forward for your subsequent submit, I will try to get the cling of it!

    Like

Leave a comment