Reputation: 19
I have got one problem with Python. I'm trying to repeat a for loop more than once. I have a condition inside the loop, and if the condition is true, the loop should start again. I need the solution only with one for loop. For example:
for i in range (10):
if i==4:
i=0
print(i)
Unfortunately this doesn't work.
The output should be: 0 1 2 3 0 1 2 3 0 1 2 3...
Upvotes: 0
Views: 10298
Reputation: 107347
Converting the through away variable i
to 0 at the bottom level of the loop doesn't mean that in next iteration your variable shall be 0, because in each iteration python reassigned it automatically.
As a more pythonic way for such tasks you can use itertools.cycle
>>> def range_printer(r,N): # r is the length of your range and N is the number of sequence printing
... a=cycle(range(r))
... for i in range(N*r):
... print next(a)
...
>>> range_printer(4,3)
0
1
2
3
0
1
2
3
0
1
2
3
Or you can use yield
to return a generator :
>>> def range_printer(r,N):
... a=cycle(range(r))
... for i in range(N*r):
... yield next(a)
...
>>> list(range_printer(4,3))
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
Upvotes: 2
Reputation: 46921
a version using itertools.cycle
:
from itertools import cycle
for i in cycle(range(4)):
# put your logic that `break`s the cycle here
print(i)
Upvotes: 2
Reputation: 31349
Writing to the loop's variable (i
) inside the loop is always not a good idea (that includes all languages I'm familiar with).
Try using a while loop instead:
i = 0
while i < 10:
i += 1
if i == 4:
i = 0
The same logic can be implemented with:
while True:
for i in range(4):
print(i)
Or using the modulo operator which is common when cycling:
i = 0
while True:
print(i % 4)
i += 1
Upvotes: 4