rsnaveen
rsnaveen

Reputation: 333

skip every nth value when looping over a range - python

Let's say I have something like this.

for i in range((n**2)+(n-1)):
    print i,

Here

n = any integer after one(2, 3, 4 etc.)

Now, if n is 2, I'll get values of i as 0, 1, 2, 3, 4.

What I need is to be able to skip every nth value of i so that, if n is 2, my output will be 0, 1, 3, 4 and if n = 3, my output will be 0, 1, 2, 4, 5, 6, 8, 9, 10

Thank you.

Upvotes: 0

Views: 9465

Answers (2)

rsnaveen
rsnaveen

Reputation: 333

Based on what Brian Cain said, I have found the solution for my question. Thanks Brian. The following is the code I was looking for:

for i in range ((n**2)+(n-1)):
    if (i+1) % (n+1) == 0 and i != 0:
        continue
    print i

Upvotes: 0

Brian Cain
Brian Cain

Reputation: 966

One such way to do that is just skip the iterations of the loop you don't want to iterate with a continue statement

for i in range(0,11):
    if i % 3 == 0 and i != 0:
        continue
    print(i)


1
2
4
5
7
8
10

Upvotes: 4

Related Questions