Bassem
Bassem

Reputation: 51

Infinite python generator

I have been leaning python and programming for not so long. So you may find my question silly. I am reviewing generator and try to generate 'yes', 'no' infinitely just to understand the concept.

I have tried this code but having "yes" each time

def yes_or_no():
    answer = ["yes","no"]
    i=0
    while True:
        if i >=2:
            i=0
        yield answer[i]
        i+=1

c=next(yes_or_no())

print(c)
print(c)
print(c)
print(c)

Upvotes: 3

Views: 610

Answers (3)

Jab
Jab

Reputation: 27485

While your function does return a generator and it has been stated by others that all you need to do is iterate over it using a loop or calling next in succession. Python provides you a great library called itertools to do exactly this thing; it's called itertools.cycle. This is all the code you need to replicate your functions ability:

def yes_no():
    return itertools.cycle(['yes', 'no'])

And just like others have said, a generator can be iterated over using next or a loop.

>>> c = yes_no()
>>> next(c) 
'yes'
>>> next(c) 
'no'
...

Upvotes: 1

heemayl
heemayl

Reputation: 41987

You need to initialize the generator and then call next on the initialized generator object:

c = yes_or_no()

Now you need to call next on c:

print(next(c))
print(next(c))

In your current code c=next(yes_or_no()):

  • yes_or_no() will initialize the generator and calling next on it will get the first yes and you're saving that yes as name c

  • In the next lines, you're just printing same yes referred by c while doing print(c)

Upvotes: 1

chepner
chepner

Reputation: 530872

yes_no() produces the generator; you want to call next on the same generator each time, rather than printing the same first element over and over.

c = yes_no()

print(next(c))
print(next(c))
# etc.

That said, there's no need for a separate counter; just yield yes, then yield no, then repeat.

def yes_or_no():
    while True:
        yield "yes"
        yield "no"

Upvotes: 5

Related Questions