Processing math: 100%

First time here? Check out the FAQ!

Ask Your Question
1

How to skip a single loop iteration

asked 6 years ago

MarioM gravatar image

I have the following code:

 for k in range(9):
    if k != 3:
        print(k)
    else:
        print(20)
        # i want to skip the next iteration

So I want to get: 0,1,2,20,5,6,7,8, here I skip the fourth iteration. I already try to use the command next(), but it doesn't give what I want

Preview: (hide)

3 Answers

Sort by » oldest newest most voted
1

answered 6 years ago

joaoff gravatar image

Is that all you want?

One way to do that.

for k in range(9):
    if k != 3:
        if k != 4:
            print(k)
        else:
            pass
    else:
        print(20)
        # i want to skip the next iteration
Preview: (hide)
link

Comments

the

else:
    pass

can be removed... the whole thing is equivalent to

for k in range(9):
    if k != 3:
        print(k)
    elif k != 4:
        print(20)
vdelecroix gravatar imagevdelecroix ( 6 years ago )
1

answered 6 years ago

vdelecroix gravatar image

The following

R = iter(range(9))
for r in R:
    if r == 3:
        a = next(R)   # remove the next element from the iterator
    print(r)

produces

0
1
2
3
5
6
7
8
Preview: (hide)
link
0

answered 6 years ago

dan_fulea gravatar image

Depending on the real need, the one or the other of the following code snippets may be preferable.

(1) Arrange the range.

R = [0..2] + [20] + [5..8]
for r in R:
    print r

(2) Define a function that does the right thing for the right k:

def f(k):
    if k == 3:    print 20
    elif k == 4:    pass
    else:    print k

for k in [0..8]:
    f(k)

(3) Do the same as above without function.

for k in [0..8]:
    if k == 4:    continue
    elif k == 3:    print 20
    else:    print k

(4) If in the real application we have no good control of the position, after that we skip, we can use a flag, skipNext say...

def myCondition(k): if k == 3: return True return False

nextSkip = False for k in range(9): oldSkip = nextSkip nextSkip = myCondition(k) if oldSkip: continue if nextSkip: print 20 else: print k

You see how hard is to guess the "needed solution". The question is a pure python question, consider reviewing data structures in python and logical ramification possibilites.

Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 6 years ago

Seen: 680 times

Last updated: Jul 06 '18