0

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
5
  • 3
    And does it "produce x infinitely"? You did try it? Commented Mar 6, 2018 at 12:37
  • 1
    Is there any question ? Commented Mar 6, 2018 at 12:38
  • 2
    Thanks for telling us that you are trying to make an infinite loop. Commented Mar 6, 2018 at 12:51
  • You can use any of the infinite Iterators in 'itertools'. More here: docs.python.org/2/library/itertools.html Commented Mar 6, 2018 at 13:35
  • Yes I have tested it. Commented Mar 6, 2018 at 13:54

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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()

Comments

1

Update list after each iteration make infinite loop

list=[0] 
for x in list:
    list.append(x+1)
    print (x)

2 Comments

I upvoted, but I also invite you to elaborate a little more. I think that some explaination may help the OP to understand the concept behind your solution, and why its use of range is not working.
Even though this works as intended, it is generally considered bad practice to add/remove elements to/from an array you are iterating over.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.