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:
Expected Output:
Using the continue Statement
Let’s use a for loop and apply continue to skip multiples of 5:
Output:
Explanation:
-
When
xis a multiple of 5 (like 10 or 15), the loop skips the print statement usingcontinue. -
All other numbers are printed normally.
Alternate Solution Without continue
You can also solve the same problem using a regular if condition:
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
Output:
Explanation:
-
When
ibecomes 3, the program skips printing and jumps to the next iteration.
Final Exercise: Combining continue and break
Output:
How It Works:
-
10: Multiple of 5 → skipped
-
16, 17, 18, 9: Printed
-
15: Multiple of 5 → skipped
-
21: Multiple of 7 → triggers
breakand exits the loop -
"Bye"is printed after the loop ends.