The Python continue statement is another way to control the flow of loops by skipping the current iteration. Like the Break statement, the continue statement is used inside for loops and while Loops.
While executing the iterables, if the controller encounters the Python continue statement inside them, the control will stop the current iteration and immediately move to the next iteration from the beginning.
Python continue Syntax
The basic syntax of the continue statement is
continue
As you can see from the syntax above, the keyword continue is placed on a separate line. By default, the continue statement can be used only inside a for loop or a while loop. Otherwise, it throws a syntax error.
The syntax of the Python continue statement inside a for loop is shown below.
for item in itearable:
if condition:
continue
# code
The following syntax illustrates the continue statement inside a while loop.
while expression:
if condition:
continue
# code
How Python continue work internally?
As we mentioned earlier, the continue statement must be used inside a loop. To add a continue statement, we need to define a condition that has to be met. It means the starting point is a loop, and to ease things, we consider a for loop.
- The starting entry point for the control is the loop, and the control starts executing the code inside the loop.
- When the controller encounters the continue statement, it immediately stops the current iteration.
- Any statements inside a loop after the continue statement will be skipped completely.
- Loop control jumps to the starting position to start the new iteration.
TIP: Generally, we use the Python continue statement in conjunction with the if statement. Where the if statement checks the condition, and if it is true, execute the continue statement.
In the next section, we share two examples to demonstrate the working functionality of the continue statement in both for loops and while loops.
Python continue Statement in a for Loop
As we mentioned earlier, the continue statement skips the current step and moves the control to the next iteration. Before we step into the example, let me show you the necessity of using a continue statement. For example, the code below prints the numbers from 1 to 9.
number = 10
for i in range (1, number):
print(i, end = ' ')
1 2 3 4 5 6 7 8 9
However, we only need even numbers as the output, and the odd numbers have to be skipped from the display. In such a situation, we can use the Python continue statement inside a for loop. The following example demonstrates it.
This program allows the user to enter any integer value and store it in a variable (number). In the next line, we used a for Loop with a range function to iterate over the range of items from 1 to user given number (n).
Inside a for loop, we placed the if condition (i%2 != 0) to test whether the number at each iteration is not divisible by zero (odd number). For each for loop iteration, this condition must be evaluated.
If this condition is True, the Python continue statement in the for loop will execute. The iteration will stop at that number without executing the other print statements: print(” Even numbers = “, i). For better understanding, we placed a print message inside the if statement. Whenever the iteration breaks, the value will display from this print function.
If the condition is false, it will skip the continue keyword and print that number as output (In our case, an Even Number) using the following block of code.
number = int(input("Please Enter integer Value: "))
for i in range (1, number):
if i % 2 != 0:
print("Odd Numbers = {0} (Skipped)".format(i))
continue
print("Even numbers = ", i)
Please Enter integer Value: 8
Odd Numbers = 1 (Skipped)
Even numbers = 2
Odd Numbers = 3 (Skipped)
Even numbers = 4
Odd Numbers = 5 (Skipped)
Even numbers = 6
Odd Numbers = 7 (Skipped)
TIP: Please refer to the Break Statement to understand the implementation of the Python break inside the For loop and While loop.
In the example below, we use a for loop to iterate over the characters in a string. Within the for loop, the if statement checks whether the character is ‘t’ or ‘a’. If true, the Python continue statement inside the for loop executes and skips printing that character.
text = "tutorialgateway"
for c in text:
if c == 't' or c == 'a':
continue
print(c, end = ' ')
u o r i l g e w y
Impact of the Python continue statement with an else clause
When working with loops and the continue statement, both the while loop and the for loop have an else clause. However, the impact of the continue statement is zero because the else block executes after executing all loop iterations. On the other hand, the continue statement impacts the loop iterations.
The for loop in the example below iterates over the range of numbers from 0 to 9. The if statement checks whether the number is odd. If true, the continue statement skips that number. Otherwise, the print statement displays that number. Once the iterations are complete (number becomes 10), the loop terminates, and the message in the else block executes. Therefore, the else block has zero impact on the continue statement.
for n in range(10):
if n % 2 != 0:
continue
print(n, end = ' ')
else:
print("\nLoop Ended")
0 2 4 6 8
Loop Ended
Python continue in a while Loop
Unlike a for loop, we must manually control the loop counter variable, so in a while loop, the continue statement behaves differently.
In this example, we will show how to use the continue statement inside a while loop. This program will iterate from 1 to 10 and print every number up to 10. We also used the if condition to skip a few numbers.
i = 0
while(i <= 10):
if (i== 5 or i == 9):
print("Skipped Values = ", i)
i = i + 1
continue
print(" The Value of the Variable i is: ", i)
i = i + 1

In this while loop continue program example, we initialized the i value as 0. Next, we used the while loop condition to check whether the i value is less than or equal to 10.
Inside the While Loop, we placed the If expression to test whether i is equal to 5 or 9. If this condition is True, then the Python continue statement will be executed. Next, the iteration will stop at that number without executing the next two lines:
We placed the following print function inside the if condition for better understanding. Whenever the iteration breaks with the continue statement, that value will be printed as output.
If the condition is false, then it will skip this and print that number as output (In our case, 0, 1, 2, 3, 4, 6, 7, 8, 10)
NOTE: We also used the Arithmetic Operator + operator in this example to increment the i value (i = i + 1). If you forget this line, you will end up in an infinite loop.
Unintentional infinite loop with continue Example
When working with the Python continue statement in a while loop, there is a danger of getting into an infinite loop. For example, the code below runs infinitely.
On each iteration, the while loop checks whether the I value is less than 5. The if statement checks whether i equals 2. If True, the continue statement executes and skips the next two statements (i += 1 and print statement).
Here, we are executing the continue statement without incrementing the i value, and the loop will not stop. There is no i += 1 execution.
i = 0
while i < 5:
if i == 2:
continue
i += 1
print(i, end = ' ')
There are two approaches to fix this problem; the previous example is the first approach. However, the program mentioned below is the best approach.
Here, we incremented the i value at the starting position, then used the continue statement to skip the numbers.
i = 0
while i < 5:
i += 1
if i == 2:
continue
print(i, end = ' ')
1 3 4 5
Python continue statement in nested loops
We can also use the continue statement inside the nested while loops or nested for loops. The behaviour of skipping the current iteration is the same. However, the step skipping process is limited to the nested.
TIP: In short, the continue statement skips the iteration of the current loop.
In the example below, we use nested for loops, where the first one iterates from zero to 1. The second for loop iterates from zero to 4. Inside the nested loop, we use the if statement to check whether the J value is 1 or 3. If either of them is True, the control will execute the Python continue statement to skip that number and proceed to the next iteration of the nested. Once the J becomes 5, the control will move to the outer loop.
for i in range(2):
for j in range(5):
if j == 1 or j == 3:
continue
print(f"i={i}, j={j}")
As you can see from the result, the j values are skipped, but the i value is intact.
i=0, j=0
i=0, j=2
i=0, j=4
i=1, j=0
i=1, j=2
i=1, j=4
In the example below, we added one continue statement in the outer loop. It means, when i become 1, the continue statement completely skips the execution of the nested loop.
for i in range(3):
if i == 1:
continue
for j in range(5):
if j == 1 or j == 3:
continue
print(f"i={i}, j={j}")
i=0, j=0
i=0, j=2
i=0, j=4
i=2, j=0
i=2, j=2
i=2, j=4
Python continue statement real-world examples
The following are some examples of the continue statement to skip unwanted items.
Skipping even numbers
The following example uses the continue statement in a for loop to skip printing even numbers in a range. It is the same as the first example, and we have already explained the code.
for n in range(1, 11):
if n % 2 == 0:
continue
print(n, end = ' ')
1 3 5 7 9
Use Python Continue in the SaaS Billing
In the example below, we declared a dictionary with users and the payment status. In this SaaS billing example, the continue statement skips users who have not paid for the subscription and generates the invoice for the paid customers.
subscriptions = [
{"user": "John", "paid": True},
{"user": "Mike", "paid": False},
{"user": "Tracy", "paid": True}
]
for sub in subscriptions:
if not sub["paid"]:
continue
print(f"Invoice Generated for {sub['user']}")
Invoice Generated for John
Invoice Generated for Tracy
Use Continue in System Authentication
Similar to the above, we can use the Python continue statement in system authentication to skip inactive users.
users = [
{"user": "John", "active": True},
{"user": "Mike", "active": False},
{"user": "Tracy", "active": True}
]
for sub in users:
if not sub["active"]:
continue
print(f"Authenticate {sub['user']}")
Authenticate John
Authenticate Tracy
Skipping negative numbers from math calculations
When working with the mathematical calculations, there are situations where we must skip the negative numbers. For example, when calculating the square root of a number, if it encounters any negative value, the sqrt() function will raise an error. To avoid this, we must skip the negative numbers using a Python continue statement.
In the example below, the if condition inside the for loop checks whether the list element is less than zero. If True, the continue statement skips that number from the math module, calculating the square root.
import math
numbers = [49, 16, -16, 4, -10, 25, 9]
for n in numbers:
if n < 0:
continue
print("Square Root = ", math.sqrt(n))
Square Root = 7.0
Square Root = 4.0
Square Root = 2.0
Square Root = 5.0
Square Root = 3.0
Use Python continue inside try/except
In the Python programming language, we can use the continue statement inside a try/except block to handle errors in a loop. In the example below, the for loop iterates over the list of numbers, where one of the values is 0.
Within the try block, we are dividing 100 by each list number. When it reaches 0, it will throw a ZeroDivisionError error. The except catches it, and the continue statement will skip that number.
numbers = [2, 5, 0, 10]
for n in numbers:
try:
result = 100 / n
except ZeroDivisionError:
print("Divide by zero Issue")
continue
print(result)
50.0
20.0
Divide by zero Issue
10.0
Handling Invalid User Input using continue
When accepting user inputs, we can use the combination of the continue statement and the break statement to handle invalid or unwanted data.
In the example below, the while True condition is always True. The if condition uses the isdigit() function and checks whether the given number is a digit or not. If it is not a digit, the Python continue statement skips that entry and asks the user to enter again. When the user enters a number, the break statement will terminate the loop.
while True:
n = input("Enter a number: ")
if not n.isdigit():
print("Not a number. Try Again!")
continue
value = int(n)
print("Entered Number =", value)
break
Enter a number: T
Not a number. Try Again!
Enter a number: 10
Entered Number = 10
continue to Filter the API response codes
When working with APIs, we may encounter a variety of response codes, including 200, 301, and others. However, we only need the APIs that return 200 (valid ones), so we use the continue statement to skip processing API’s returning other than a 200 response code.
APIresponses = [
{"status": 200},
{"status": 500},
{"status": 200},
{"status": 404},
{"status": 410}
]
for res in APIresponses:
if res["status"] != 200:
continue
print("Process successful response")
Process successful response
Process successful response
Python continue vs pass statement
Generally, people confuse the continue statement and the pass statement. However, they are distinct and serve different purposes.
| continue | pass |
|---|---|
| The syntax involves a keyword: continue | The syntax involves a keyword: pass |
| When the control encounters the continue statement, it skips the current iteration and moves to the next iteration. | On the other hand, when control encounters the pass statement, it does nothing and continues execution. |
| It skips the iteration. | It does nothing. |
Example using the pass statement
The following example is supposed to print the numbers from 0 to 4. Here, we used the first statement to check whether the value on each iteration equals 3. If True, execute the pass statement.
As we all know, there is a number 3 between 0 and 4. However, the pass statement does nothing and prints the numbers 0, 1, 2, 3, and 4.
for n in range(5):
if n == 3:
pass
print(n, end = ' ')
0 1 2 3 4
Example using the continue statement
We use the same example and replace the pass statement with the Python continue statement. It skips 3 and prints the remaining numbers.
for n in range(5):
if n == 3:
continue
print(n, end = ' ')
0 1 2 4