Continue Statement in Python

In Python, the continue statement allows you to skip the current iteration of a loop and move directly to the next one.

continue

Unlike the break statement, continue doesn't completely exit the loop but rather stops the current iteration prematurely, allowing the next iteration to begin in both for and while loops.

    Practical Examples

    Example 1 (for loop)

    This script performs seven iterations (from 1 to 7) using a FOR loop.

    The loop includes a print statement that outputs the current loop number to the screen.

    1. for i in range(1, 8):
    2. if i == 5: continue
    3. print(i)

    During the fifth iteration, the IF statement triggers the continue instruction, which skips this iteration and returns control to the FOR loop to start the sixth iteration.

    As a result, the script's output is:

    1
    2
    3
    4
    6
    7

    The number 5 is missing from the output because the fifth iteration was skipped by the continue statement before the print(i) statement could execute.

    Example 2 (while loop)

    This script performs the same operation as the previous example, but using a while loop.

    1. i = 0
    2. while i < 7:
    3. i += 1
    4. if i == 5: continue
    5. print(i)

    In the fifth iteration, the continue statement skips the current iteration and proceeds to the next one.

    The output of this script is:

    1
    2
    3
    4
    6
    7

    Again, the number 5 is missing because the iteration was skipped before completing.

    And so on.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Loop Structures in Python

    Forced Interruptions and clauses