Skip to main content
Practice

Skip Iteration with continue

continue is used to terminate the current iteration and proceed to the next one.

When continue is encountered inside a loop, the code following it is not executed, and the loop condition is re-evaluated to continue with the next iteration.

It is often used when you want to skip certain processes under specific conditions.


Example of using continue

Skip the current iteration with continue
# Loop from 1 to 10
for i in range(1, 11):
# If the remainder of i divided by 2 is 0, it's an even number
if i % 2 == 0:
# Skip the iteration when the number is even
continue
# Print only odd numbers
print(i)
Output
1
3
5
7
9

i % 2 == 0 checks if i is divisible by 2.

The % operator is the modulus or remainder operator, so i % 2 returns the remainder of i divided by 2. If i is even, this will be 0.

In Python, 0 is considered False within an if statement, so if i % 2 == 0: will be True for even numbers.

Thus, whenever i is even, the continue statement is triggered, causing the loop to skip the remaining code for that iteration.

This method ensures that the loop prints only the odd numbers between 1 and 10.


Practical Programming Example

continue is particularly useful when you want to execute code only under certain conditions while iterating through elements.

For example, you can use continue if you want to skip certain characters while iterating through the characters of a string.

Skip specific character
text = "Banana"

# Iterate through each character in the string and skip 'a'
for char in text:
# When the character is 'a'
if char == "a":
# Skip the iteration
continue
# Print the character
print(char)
Output
B
n
n

In this example, all instances of the character 'a' are skipped, and only the remaining characters are printed.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.