How To Skip A Number In A For Loop Python

In this tutorial, we will learn how to skip a specific number while iterating through a for loop in Python. Skipping a number in a for loop can be helpful in cases where you need to filter out or ignore specific values in a sequence or range. To accomplish this, we will use Python’s built-in continue statement.

Step 1: Understand the continuing statement

The continue statement is used in a loop to skip the current iteration and jump to the next iteration directly. It is commonly used in combination with a conditional statement to skip a particular value or range of values in a loop.

Let’s use an example to understand the working of the continue statement:

Output:

1
2
3
4
6
7
8
9
10

In this example, we have a for loop that iterates over the numbers from 1 to 10. Inside the loop, we have an if statement that checks if the current number i is equal to 5. If it is, we use the continue statement to skip the current iteration and jump to the next. As a result, the number 5 is not printed.

Step 2: Write a for loop with a continue statement

Now, let’s create a for loop using the continue statement to skip multiple numbers:

Output:

1
3
5
7
8
9
10

In this example, we have a for loop that iterates over the numbers from 1 to 10. We use an if statement to check if the current number i is present in the list [2, 4, 6]. If it is, we use the continue statement to skip the current iteration and jump to the next. As a result, the numbers 2, 4, and 6 are not printed.