How to Skip Numbers in a Python Loop?

Estimated read time 2 min read

To skip numbers in a Python loop, you can use the continue statement to skip a specific number or range of numbers that you do not want to process in the loop. You can use an if statement to check if the current number is the one you want to skip, and use the continue statement to skip that number and move on to the next iteration.

Here’s an example of using the continue statement to skip specific numbers in a Python loop:

# loop through a range of numbers and skip multiples of 3
for i in range(1, 10):
    if i % 3 == 0:
        continue
    print(i)

In this example, we loop through a range of numbers from 1 to 9 using a for loop and the range() function. Inside the loop, we use an if statement to check if the current number i is a multiple of 3 (i.e., if the remainder of i divided by 3 is 0). If i is a multiple of 3, we use the continue statement to skip the remaining code in the current iteration and move on to the next iteration. If i is not a multiple of 3, we print the number.

The output of this code is:

1
2
4
5
7
8

Note that in this example, we use the range() function to generate a sequence of integers from 1 to 9, and we skip any number that is a multiple of 3. You can modify the condition in the if statement to skip different numbers or ranges of numbers as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply