So I'm trying to make a infinite loop that uses a for loop instead of a while loop. This is my current code. If this code works it should produce x infinitely. Current code:
z=1
for x in range(0,z):
print(x)
z=z+1
So I'm trying to make a infinite loop that uses a for loop instead of a while loop. This is my current code. If this code works it should produce x infinitely. Current code:
z=1
for x in range(0,z):
print(x)
z=z+1
That doesn't work because the first time you enter the for loop the range function generates a range from zero to the value of z at that point, and later changes to z does not affect it. You can do something like what you want using, for example, itertools.count:
from itertools import count
for x in count():
print(x)
range returns an iterator. The iterator is already generated and evaluated before the loop iteration. (It's the returned iterator on which the loop is iterating).
The value of z is not used after the iterator is returned hence incrementing or changing its value is no-op.
If you really want an infinite loop using for you will have to write your custom generator.
For eg:
def InfiniteLoop():
yield 1
To be used as :
for i in InfiniteLoop()
Update list after each iteration make infinite loop
list=[0]
for x in list:
list.append(x+1)
print (x)