continue statement

The continue statement inside a for or while construct makes the control to transfer to the immediate enclosing loop

Continue Updated 22 Jan 2017 1 min read

Overview

The continue statement in python can appear inside for or while loop.

When a continue statement is executed control is transferred to the

immediate enclosing loop.

Examples for Continue in Python

Example1

python
def printList(listobject):

    for element in listobject:

        #continue if an element is None

        if element is None:

            continue

        #print only if an element is valid

        print(element)

randomList = [18,9,None,4,37,26,None]

printList(randomList)

Output1

python
18

9

4

37

26

In the above example while printing a python list object any element with the value None is omitted by using the continue statement.

Example2

python
def pythonFunction():

    dictObject = {"a":[1,2],  "c":None, "b":"2",}

    for elem in dictObject:

        try:

            if len(dictObject[elem]) > 1:

                continue

            print(dictObject[elem])

        except:

            print("In catch now")

        finally:

            print("In finally now")

pythonFunction()

Output2

python
In finally now

In catch now

In finally now

2

In finally now

If continue is executed inside a try block and if the try block has an associated except block and a finally block those blocks will be executed before continuing with the next iteration of the loop.

In the above example the dictionary key “2” has a value of None. Calling len function on a None has raised an exception, however, the except and finally blocks are executed before the iteration continues with the next element of the dictionary.

Also the continue statement cannot appear without a scope of for or while construct.