0

is there any way to send the value of a for look back in few loops..

for i in range(10):
    print(i)
    if random.randint(0,9) in [5,6]:
        i = 0

what i want to do is exactly something like this. now here i know the range(10) generates the range [0,1,2,3,4,5,6,7,8,9] first the then traverse it by assigning the value to i. so simply changing the value of i will not work.

but is there any other way to change i in a way that the value in the next loop will i+1

Eshaka
  • 974
  • 1
  • 14
  • 38
  • 4
    seems only using while loop can be achieved what you wants. – Saleem Ali Oct 22 '19 at 08:57
  • What output are you actually trying to get? – Sayse Oct 22 '19 at 08:57
  • @Sayse I don't think the output is actually significant here - it could be the numbers 0 - 9 or an infinite output, or somewhere in between... I think the OPs is using it as an example of the kind of control flow they'd like to achieve – Jon Clements Oct 22 '19 at 08:59
  • what i am trying to do is something completely different from this code.. i just wrote this so that its easy to read.. i just didnt think of a while loop in this case.. i will use a while loop and i think i can get my function to work – Eshaka Oct 22 '19 at 08:59
  • put please.. let me know if it is possible to achieve using a for loop too – Eshaka Oct 22 '19 at 09:00
  • all three of these answers are the same.. sorry guys.. but i think i am gonna wait for someone to do it will a for loop.. if possible. i already wrote the while loop by my self.. :) – Eshaka Oct 22 '19 at 09:03

2 Answers2

1

Instead of a for loop, you can do a while loop by declaring i outside the loop.

i = 0
while i < 10:
    print(i)
    if random.randint(0,9) in [5,6]:
        i = 0
    else:
        i += 1

With this, and a bit of tweaking, I think you can get the result you wanted.

Seraph Wedd
  • 864
  • 6
  • 14
0

This will work

import random
i = 0
while i < 10:
    print(i)
    if random.randint(0,9) in [5,6]:
        i = 0
    else:
        i +=1

Edit: my bad, it won't work indeed, while loop will.

S. L.
  • 630
  • 8
  • 19