Continue statement

Continue Statement in Python

In Python, loops can be controlled using jump statements such as continue. The continue statement is used to skip the current iteration of a loop and move to the next one immediately, without executing the remaining code in that iteration.


Understanding continue with an Example

Problem Statement:

Print all numbers from a list that are not multiples of 5.

Input:

L = [10, 16, 17, 18, 19, 15]

Expected Output:

16 17 18 19

Using the continue Statement

Let’s use a for loop and apply continue to skip multiples of 5:

l = [10, 16, 17, 18, 19, 15] for x in l: if x % 5 == 0: continue print(x)

Output:

16 17 18 19

Explanation:

  • When x is a multiple of 5 (like 10 or 15), the loop skips the print statement using continue.

  • All other numbers are printed normally.


Alternate Solution Without continue

You can also solve the same problem using a regular if condition:

l = [10, 16, 17, 18, 19, 15] for x in l: if x % 5 != 0: print(x)

This method directly checks if the number is not a multiple of 5 before printing it.


When to Use continue

Using continue is optional, but it is helpful for skipping specific cases in loops, especially when you have multiple operations and want to avoid nesting too many if statements.

Use Case:

In a real-world scenario, such as displaying items in an online store, if a product doesn’t have a price, you may want to skip it using continue to avoid displaying incomplete details.


Example: continue with while Loop

i = 0 while i <= 5: if i == 3: i += 1 continue print(i, i * i) i += 1

Output:

0 0 1 1 2 4 4 16 5 25

Explanation:

  • When i becomes 3, the program skips printing and jumps to the next iteration.


Final Exercise: Combining continue and break

l = [10, 16, 17, 18, 9, 15, 21, 13] for x in l: if x % 5 == 0: continue if x % 7 == 0: break print(x) print("Bye")

Output:

16 17 18 9 Bye

How It Works:

  • 10: Multiple of 5 → skipped

  • 16, 17, 18, 9: Printed

  • 15: Multiple of 5 → skipped

  • 21: Multiple of 7 → triggers break and exits the loop

  • "Bye" is printed after the loop ends.

Popular Posts