1

I have a for loop that iterates through a range, but I would like it to skip a number of iterations based on a condition. This is the code:

for i in range(1,100):

    if some_condition:
        i += some_number

What I am trying to accomplish: So let's say i=5 the some_condition is triggered and some_number=2, this would set i= 7, and then the next i that we iterate to will be 8, so we never iterate through 6 and 7. How can I do this?

2
  • 1
    Use a while loop instead. i = 1 while i < 100: ... i += 1 then you can adjust the value of i inside the loop Commented Mar 14, 2021 at 3:22
  • @Nick Thank you! I should have thought of that! Commented Mar 14, 2021 at 3:29

1 Answer 1

5

It might be easier to use a while loop:

increment = 2

i = 1
while i < 100:
    if some_condition:
        i += increment
    i += 1

Since a for loop reassigns the iterator to the next item in the iterable, whatever you do in the for clause has no effect on the iterator the next time the loop iterates.

Sign up to request clarification or add additional context in comments.

3 Comments

@Nick Good point. Actually, I think OP wanted i to increment by 1 even if the condition is True.
duh! a while loop! (after 14 hours of working on this program I am clearly losing my mind lol) thank you!
@Kat No problem! Happens to the best of us :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.