Your Page Title
🔍

    Python Continue Statement

    The continue statement in Python is used inside loops, such as for or while, to skip the rest of the codes within the same iteration and continue on to the next iteration of a loop. It is usually used where you want to bypass certain conditions or values without breaking out of the whole loop.

    Syntax:

    continue

    Key Points:

    • Skipping Iteration:

    First, the continue statement causes the program to immediately jump to the next iteration of the loop.

    • Placement:

    The placement normally is inside a condition statement of the loop.

    • Does Not Leave the Loop:

    In contrast to break that completely terminates the loop, continue will only skip out of the present iteration.

    Example 1: Skipping Even Numbers

    for i in range(1, 6):  # Loop through numbers 1 to 5
        if i % 2 == 0:    # Check if the number is even
           continue   # Skip the rest of the code for even numbers
        print(i)

    Output:

    1
    3
    5

    Here, the continue statement skips the print(i) line where i is an even number.

    Example 2: Using continue in a while Loop

    i = 0
    while i < 5:
       i += 1
       if i == 3:
         continue  # Skip the iteration when i equals 3
       print(i)

    Output:

    1
    2
    4
    5

    When i is 3 the continue statement is invoked; it does not consider to print(i) on that loop cycle.

    Practical Example: Skipping Invalid Input

    user_inputs = ["123", "abc", "456", "def"]
    for item in user_inputs:
        if not item.isdigit(): # Check if the input is not numeric
           continue # Skip non-numeric inputs
        print(f"Valid number: {item}")

    Output:

    Valid number: 123
    Valid number: 456

    Here, continue skips over non-numeric inputs like "abc" and "def".

    Summary:

    • Purpose:

    Skips some iterations based on the conditions.

    • Use Case:

    When specific conditions need to be bypassed during iteration but the loop has to continue.

    • Limitation:

    It does not exit the loop; it just moves on to the next iteration.