Continue Statement

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:

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:

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:

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:

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.


Copyright 2019 © pythontic.com