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?

Dylan Ong
  • 786
  • 2
  • 6
  • 14
  • 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. – Mark Jul 09 '23 at 04:14
  • [Why doesn't modifying the iteration variable affect subsequent iterations?](https://stackoverflow.com/questions/15363138/) – Ignatius Reilly Jul 09 '23 at 04: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 – Bob Jul 09 '23 at 05:56
  • If you enter or paste the code into [link](https://pythontutor.com/visualize.html#mode=edit) 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. – user19077881 Jul 09 '23 at 06:05

3 Answers3

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
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.

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
-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

gh0st
  • 1
  • 3