pythonfor-loop

What's the difference between pass and continue in python


My test shows that both pass and continue can be used equivalently to construct a empty for-loop for test purpose. Are there any difference between them?


Solution

  • The pass keyword is a "no-operation" keyword. It does exactly nothing. It's often used as a placeholder for code which will be added later:

    if response == "yes":
        pass  # add "yes" code later.
    

    The continue keyword, on the other hand, is used to restart a loop at the control point, such as with:

    for i in range(10):
        if i % 2 == 0:
            continue
        print(i)
    

    That loop will only output the odd numbers since continue returns to the loop control statement (for) for iterations where i is even.

    Contrast that with the exact same code, but using pass in place of continue:

    for i in range(10):
        if i % 2 == 0:
            pass
        print(i)
    

    That loop prints all the numbers in the range, since pass does not return to the loop control statement for even (or any) values of i. It simply drops through to the print statement.

    In terms of an empty for loop, you're correct that they're functionally identical. You can use either of:

    for i in range(10):
        pass
    for i in range(10):
        continue