How can I do this in python:
x = [1,2,3,4,5,6]
for i in x:
if i == 4:
-restart the loop from beginning-
else:
print i
So here it will print till 4 then repeat the loop
How can I do this in python:
x = [1,2,3,4,5,6]
for i in x:
if i == 4:
-restart the loop from beginning-
else:
print i
So here it will print till 4 then repeat the loop
What about this:
x = [1,2,3,4,5,6]
restart = True
while restart:
for i in x:
# add any exit condition!
# if foo == bar:
# restart = False
# break
if i == 4:
break
else:
print i
Something like this perhaps? But it will loop forever...
x = [ ..... ]
restart = True
while restart:
for i in x:
if i == 4:
restart = True
break
restart = False
print i
You can't directly. Use itertools.cycle
for idx, val in enumerate(itertools.cycle(range(4))):
print v
if idx>20:
break
idx is used to break infiniteloop
Just wrap in a while statement.
while True:
restart = False
for i in x:
if i == 4:
restart = True
break
else:
print i
if not restart:
break
With a while loop:
x=[1,2,3,4,5,6]
i=0
while i<len(x):
if x[i] == 4:
i=0
continue
else:
print x[i]
i+=1
I would use a recursive function for that
def fun(x):
for i in x:
if i == 4:
fun(x)
else:
print i
return;
x = [1,2,3,4,5,6]
fun(x)