0

I'm trying to increment a for loop within itself if a certain condition is met, as shown in the code below

for i in range(0,5):
   if condition == True:
      i+=1
   print(i)

If it runs as I want it to, the output should be: "1 3 5". Instead, the output is "0 1 2 3 4". Can anyone help me with this?

4
  • 2
    It's hard to see how you are getting this output unless condition is never True. It's always helpful to create an example that people can actually run. Commented Jul 9, 2023 at 4:14
  • Why doesn't modifying the iteration variable affect subsequent iterations? Commented Jul 9, 2023 at 4:21
  • Depending on what exactly your trying to do, you also might be able to use the continue statement when the condition is False. Otherwise while is the way to go as others have already stated Commented Jul 9, 2023 at 5:56
  • If you enter or paste the code into link you can see the code executing ad you step through which explains what is happening. This is a very useful approach for such code samples. Commented Jul 9, 2023 at 6:05

3 Answers 3

0

You have to do with a while loop what the for was doing for you.

i = 0
while i < 5:
   if condition == True:
      i+=1
   print(i)
   i += 1

When you do for i in xxx:, the xxx is constructed before the loop ever runs. It is going to feed new values to i regardless of what happens inside the loop.

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

Comments

0

You can skip iterator elements by creating and controlling the iterator yourself (Attempt This Online!):

condition = True

it = iter(range(0,5))
for i in it:
   if condition == True:
      i+=1
      next(it, None)
   print(i)

Though you might be better off with a while loop.

Comments

-3

Like Tim was mentioning, when you're using a for loop, the variable i is being 're-generated' at the start of each iteration, regardless of what its value was in the previous iteration. It's sort of a placeholder iterator so trying to replace it and print it's new value won't work. You could work with the iterators current value by doing something like:

for i in range(0,3):
   if condition == True:
      print(i+1)

Essentially, would have to use a while loop if you were intending to actually store or be able to modify the previous state of the variable i

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.