Question

I have problem in making generator in python(3.3.4). Here is my code:

def gene(a):

    for b in range(a):
        if b==0 or b==1:
            continue
        if a%b==0:
            yield ("This is Composite number "+str(a))

    yield ("Out!")


gio = gene(12)

When i'm using next(gio) it says "This is Composite number 12" but as I know when i use next function again the function should resume where it left off. so next(gio) should print out "out". But it is not. Help me to understand why it is happening this way.

Was it helpful?

Solution

You are yielding a string with a, the original argument to the function. b, on the other hand, will still need to step through 2, 3, 4 and 6 before the for loop is done and Python reaches the yield ("Out!") statement.

So, after 4 steps you get to Out:

>>> gio = gene(12)
>>> next(gio)
'This is Composite number 12'
>>> next(gio)
'This is Composite number 12'
>>> next(gio)
'This is Composite number 12'
>>> next(gio)
'This is Composite number 12'
>>> next(gio)
'Out!'

Had you used b in your string this would have been more obvious, perhaps:

>>> def gene(a):
...     for b in range(a):
...         if b==0 or b==1:
...             continue
...         if a%b==0:
...             yield ("This is Composite number "+str(b))
...     yield ("Out!")
... 
>>> gio = gene(12)
>>> next(gio)
'This is Composite number 2'
>>> next(gio)
'This is Composite number 3'
>>> next(gio)
'This is Composite number 4'
>>> next(gio)
'This is Composite number 6'
>>> next(gio)
'Out!'

OTHER TIPS

You need the for-loop to end to reach "Out!". If you wish to do that after finding a is composite, then you need to use break:

def gene(a):    
    for b in range(a):
        if b==0 or b==1:
            continue
        if a%b==0:
            yield ("This is Composite number "+str(a))
            break
    yield ("Out!")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top