Here you can find my writing about Python
11.7.2016
In this tutorial I show you how to make a generator in Python. A generator is a function, that will serve you a sequence: it knows what “next” means in a given context. The sequence it serves can be finite or infinite.
In this tutorial you will learn:
Prezi Presentation (takes some seconds to load): scroll through at your own speed.
a function that knows how to give you a next item A generator serves next() by using yield
>>>def my_generator():
yield "How"
yield "are"
yield "you"
yield "today"
>>>x = my_generator() # x is a generator
>>>next(x)
'How'
>>>next(x)
'are'
>>>next(x)
'you'
>>>next(x)
'today'
>>>next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>def my_generator():
yield "How"
yield "are"
yield "you"
yield "today"
>>>x = my_generator() # x is a generator
>>>
while True:
try:
next(x)
except StopIteration:
print('there is no next item')
break
'How'
'are'
'you'
'today'
there is no next item
Iterators serve from a iterable Generator generate out of the thin air
printing multiples of a number
>>>def my_multiples_of_3_generator(base):
n = 1
while True:
yield base * n
n += 1
>>>y = my_multiples_of_3_generator(3)
>>>next(y)
6
>>>next(y)
3
>>>next(y)
9
printing dividers of a number
>>>def my_divider_generator(number):
for n in range(1, number):
remainder = number % n
if remainder == 0:
yield n
>>>
while True:
try:
dividers.append(next(x))
except StopIteration:
print(dividers)
break
>>>dividers =[]
>>>x = my_divider_generator(14)
[1, 2, 7]
>>>my_iterable = ['How', 'are', 'you', 'today']
>>>x = iter(my_iterable) # x is a iterator
>>>next(x)
'you'
>>>next(x)
'How'
>>>next(x)
'are'
>>>next(x)
'today'
>>>next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration