I'm trying to learn python, reading by the book Learning Python, and came across the section of using the return
statement in generators, and I'm finding it difficult to wrap my head around it.
It says that while using the return
statement in a generator function, it will produce a StopIteration
exception to be raised, effectively ending the iteration. If a return
statement were actually to make the function return something, it would break the iteration protocol.
Here's the code sample
def geometric_progression(a, q):
k = 0
while True:
result = a * q**k
if result <= 100000:
yield result
else:
return
k += 1
for n in geometric_progression(2,5):
print(n)
Can anyone please explain it, and also how to use it further in any other context. Provide extra examples, if you may.