jadsq jadsq - 1 year ago 90
Python Question

Mimic while-loop using only for-loops in python

Having started to learn code with C, I had always assumed that for-loops and while-loops where essentialy always equivalent (as in one could always reproduce the behaviour of one using only the other). But in python while going from a for-loop to a while-loop is always trivial, I could not find a way to achieve the reverse.

Is there any way, in python, to reproduce the behaviour of a while-loop (infinite looping) using only for-loops ?

Here is a solution that doesn't work (because of the recursion limit) using a recursive generator:

def infinite_loopy():
yield "All work and no play makes Jack a dull boy"
for x in infinite_loopy():
yield x

#here starts the supposedly infinite-loop
for x in infinite_loopy():

Answer Source

You can do this by writing a non-yield iterator class:

class Infinite(object):
    def __iter__(self):
        return self

    def next(self): # For Python3, replace this with __next__
        return 1

# Loops forever
for i in Infinite():

(You can see it stalling on ideone if you have the patience - it's like watching paint dry).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download