-1
def loop():
    for i in range(10):
        if i == 3:
            i += 5
        print(i)

loop()

This code outputs "1, 2, 8, 4, 5, 6, 7, 8, 9" When i == 3, it gets set to 8. But on the next iteration, it gets reset to 4. How do I make it continue from "1, 2, 8" to "9"?

I've tried multiple things. Is there a way to use the continue keyword so it skips more than one iteration? Like this maybe:

continue * 5

Thank you in advance

Largestest
  • 51
  • 1
  • 1
    Running your code - get this output: 0 1 2 8 4 5 6 7 8 9 – Daniel Hao Feb 26 '23 at 03:16
  • 1
    This wont really work because I actually have to skip the iterations between 2 and 8 – Largestest Feb 26 '23 at 03:17
  • 1
    A different way to look at your problem is, "*how to loop over range of 1-10, but skip over 3-7*", which is a more practical problem and would lead you to better search results. – Gino Mempin Feb 26 '23 at 03:17
  • 1
    The next value of `i` has absolutely nothing to do with the previous value of `i` - it comes solely from the values produced by `range(10)`, and you have no way of affecting that. – jasonharper Feb 26 '23 at 03:24

2 Answers2

0

Make it a while loop instead.

i = 0
while i < 10:
    if i == 3:
        i += 5
    print(i)
    i += 1
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

If you need to use a for loop, you can do something like the following.

def loop():
    skip, until = False, None
    for i in range(10):
        if i == 3:
            until = i+5
            skip = True
            continue
        elif skip:
            if i!=until:
                continue
            else:
                skip, until = False, None
        print(i)

loop()

We set two variables, skip: bool and until: int. The boolean skip means it is lower than that you want to skip to (in this case 8), and until stores the value 8. If it reaches 8, it will reset the skip and until variables.

But if a for loop is not required, use a while loop.

Ex)

num = 0
while num<10:
    if num==3:
        num+=5
    else:
        num+=1
    print(num)
Jason Grace
  • 321
  • 11