In [1]:
def foo(n):
    for i in range(n):
        yield f'twice {i} is {2*i}'

In [2]:
g = foo(3)
g


Out[2]:
<generator object foo at 0x7f9dac352eb8>

In [3]:
next(g)


Out[3]:
'twice 0 is 0'

In [4]:
next(g)


Out[4]:
'twice 1 is 2'

In [5]:
next(g)


Out[5]:
'twice 2 is 4'

In [6]:
next(g)


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-6-5f315c5de15b> in <module>()
----> 1 next(g)

StopIteration: 

In [7]:
next(foo(5))


Out[7]:
'twice 0 is 0'

In [8]:
next(foo(5))


Out[8]:
'twice 0 is 0'

In [9]:
for x in foo(5):
    print(x)


twice 0 is 0
twice 1 is 2
twice 2 is 4
twice 3 is 6
twice 4 is 8